ALTER TABLE media_supply_wallet_ledgers
    ADD COLUMN IF NOT EXISTS sales_cents BIGINT NOT NULL DEFAULT 0,
    ADD COLUMN IF NOT EXISTS cost_cents BIGINT NOT NULL DEFAULT 0,
    ADD COLUMN IF NOT EXISTS gross_profit_cents BIGINT NOT NULL DEFAULT 0;

UPDATE media_supply_wallet_ledgers l
SET sales_cents = CASE
        WHEN l.reason = 'order_debit' THEN o.sell_total_cents
        WHEN l.reason = 'order_refund' THEN -o.sell_total_cents
        ELSE 0
    END,
    cost_cents = CASE
        WHEN l.reason = 'order_debit' THEN o.cost_total_cents
        WHEN l.reason = 'order_refund' THEN -o.cost_total_cents
        ELSE 0
    END,
    gross_profit_cents = CASE
        WHEN l.reason = 'order_debit' THEN o.sell_total_cents - o.cost_total_cents
        WHEN l.reason = 'order_refund' THEN -(o.sell_total_cents - o.cost_total_cents)
        ELSE 0
    END
FROM media_supply_orders o
WHERE l.order_id = o.id
  AND l.reason IN ('order_debit', 'order_refund');

ALTER TABLE media_supply_wallet_ledgers
    ADD CONSTRAINT chk_media_supply_wallet_ledger_fact_non_negative
    CHECK (
        reason = 'order_refund'
        OR (sales_cents >= 0 AND cost_cents >= 0 AND gross_profit_cents >= 0)
    ) NOT VALID;

ALTER TABLE media_supply_wallet_ledgers
    VALIDATE CONSTRAINT chk_media_supply_wallet_ledger_fact_non_negative;
