-- Preserve legacy negative matured balances as explicit carried debt.
ALTER TABLE ledger_entries
  ADD COLUMN IF NOT EXISTS currency text;
--> statement-breakpoint
ALTER TABLE wallet_vesting
  ADD COLUMN IF NOT EXISTS carried_debt_minor bigint DEFAULT 0 NOT NULL;
--> statement-breakpoint
UPDATE wallet_vesting
SET
  carried_debt_minor = carried_debt_minor + GREATEST(-matured_minor, 0),
  matured_minor = GREATEST(matured_minor, 0)
WHERE matured_minor < 0;
--> statement-breakpoint
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'wallet_vesting_matured_minor_nonneg'
  ) THEN
    ALTER TABLE wallet_vesting
      ADD CONSTRAINT wallet_vesting_matured_minor_nonneg CHECK (matured_minor >= 0);
  END IF;
END $$;
--> statement-breakpoint
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'wallet_vesting_carried_debt_minor_nonneg'
  ) THEN
    ALTER TABLE wallet_vesting
      ADD CONSTRAINT wallet_vesting_carried_debt_minor_nonneg CHECK (carried_debt_minor >= 0);
  END IF;
END $$;
