ALTER TABLE gateway_wallet_accounts
  ADD COLUMN IF NOT EXISTS total_recharged numeric NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS total_spent numeric NOT NULL DEFAULT 0;

ALTER TABLE gateway_wallet_transactions
  ADD COLUMN IF NOT EXISTS account_id uuid REFERENCES gateway_wallet_accounts(id) ON DELETE CASCADE,
  ADD COLUMN IF NOT EXISTS direction text,
  ADD COLUMN IF NOT EXISTS balance_before numeric,
  ADD COLUMN IF NOT EXISTS idempotency_key text;

DO $$
BEGIN
  IF EXISTS (
    SELECT 1
    FROM information_schema.columns
    WHERE table_name = 'gateway_wallet_transactions'
      AND column_name = 'wallet_account_id'
  ) THEN
    EXECUTE 'UPDATE gateway_wallet_transactions SET account_id = wallet_account_id WHERE account_id IS NULL';
  END IF;
END $$;

UPDATE gateway_wallet_transactions
SET direction = CASE
  WHEN transaction_type IN ('recharge', 'refund', 'credit') THEN 'credit'
  ELSE 'debit'
END
WHERE direction IS NULL;

UPDATE gateway_wallet_transactions
SET balance_before = COALESCE(balance_after, 0) + CASE
  WHEN direction = 'debit' THEN COALESCE(amount, 0)
  ELSE -COALESCE(amount, 0)
END
WHERE balance_before IS NULL;

ALTER TABLE gateway_wallet_transactions
  ALTER COLUMN direction SET DEFAULT 'debit',
  ALTER COLUMN direction SET NOT NULL,
  ALTER COLUMN balance_before SET DEFAULT 0,
  ALTER COLUMN balance_before SET NOT NULL;

CREATE INDEX IF NOT EXISTS idx_gateway_wallet_transactions_account
  ON gateway_wallet_transactions(account_id, created_at DESC);

CREATE UNIQUE INDEX IF NOT EXISTS uniq_gateway_wallet_tx_idempotency
  ON gateway_wallet_transactions(account_id, idempotency_key)
  WHERE idempotency_key IS NOT NULL;
