-- 063: Vendor obligations — what each order needs to pay out
--
-- The sizer (scripts/workers/crypto_offramp/sizer.py) writes one row per
-- downstream payment the order incurs. Two kinds:
--
--   filing_fee: paid via Relay debit card via the existing Playwright
--               filing flow. Amount includes 10% buffer for fees/slippage.
--               Links to filing_fee_reservations once funds land at Relay.
--
--   commission: paid via Relay ACH 14 days post-delivery when the
--               corresponding commission_ledger row flips to 'eligible'.
--               Amount is exact (no buffer) — agent is owed a specific
--               fixed dollar amount. Links to commission_ledger so the
--               admin dashboard can show "this $X at Relay is reserved
--               for agent Y on order Z".
--
-- The orchestrator sums pending obligations × their buffer to compute
-- needed_usd_cents for the Coinbase Prime offramp.

CREATE TABLE IF NOT EXISTS vendor_obligations (
    id                        BIGSERIAL PRIMARY KEY,
    order_id                  TEXT NOT NULL,
    order_type                TEXT NOT NULL,
    obligation_kind           TEXT NOT NULL DEFAULT 'filing_fee'
                              CHECK (obligation_kind IN ('filing_fee','commission')),
    vendor                    TEXT NOT NULL,
                              -- filing_fee: state_sos | usac | fcc_cores | nwra | neca_ocn | amb | bc_registry
                              -- commission: agent_commission
    vendor_detail             TEXT,
                              -- state code ('CA') or portal slug ('USAC-499A')
                              -- for commissions: the sales_agents.id as text
    amount_usd_cents          BIGINT NOT NULL,
    fx_buffer_bps             INT NOT NULL DEFAULT 1000,
                              -- 1000 bps = 10% default for filing_fee
                              -- 0 for commission (exact amount)
    due_by                    TIMESTAMPTZ,
    status                    TEXT NOT NULL DEFAULT 'pending'
                              CHECK (status IN ('pending','reserved','paid','waived')),
    filing_fee_reservation_id INT REFERENCES filing_fee_reservations(id),
    commission_ledger_id      INT REFERENCES commission_ledger(id),
    notes                     TEXT,
    created_at                TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at                TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_vo_order    ON vendor_obligations (order_id);
CREATE INDEX IF NOT EXISTS idx_vo_pending  ON vendor_obligations (status) WHERE status = 'pending';
CREATE INDEX IF NOT EXISTS idx_vo_kind     ON vendor_obligations (obligation_kind, status);
CREATE INDEX IF NOT EXISTS idx_vo_due_by   ON vendor_obligations (due_by) WHERE due_by IS NOT NULL AND status != 'paid';
