BEGIN;

ALTER TABLE adjustment_stocks
    ADD COLUMN IF NOT EXISTS transaction_type VARCHAR(100) NOT NULL DEFAULT 'LEGACY',
    ADD COLUMN IF NOT EXISTS function_code VARCHAR(64),
    ADD COLUMN IF NOT EXISTS price NUMERIC(15, 3) NOT NULL DEFAULT 0,
    ADD COLUMN IF NOT EXISTS grand_total NUMERIC(15, 3) NOT NULL DEFAULT 0;

UPDATE adjustment_stocks
SET function_code = CASE
    WHEN COALESCE(total_qty, 0) > 0 THEN 'ADJUSTMENT_IN'
    WHEN COALESCE(usage_qty, 0) > 0 THEN 'ADJUSTMENT_OUT'
    ELSE 'ADJUSTMENT_IN'
END
WHERE function_code IS NULL OR function_code = '';

CREATE INDEX IF NOT EXISTS idx_adjustment_stocks_transaction_type
    ON adjustment_stocks(transaction_type);

CREATE INDEX IF NOT EXISTS idx_adjustment_stocks_function_code
    ON adjustment_stocks(function_code);

COMMIT;
