-- 014_relay_deposits.sql
-- Relay deposit detection and filing fee reservation system.
--
-- Flow:
--   relay_deposit_monitor.py watches relay-deposits@performancewest.net via IMAP.
--   When Relay emails "You received $X from FID BKG SVC LLC" (Stripe payout),
--   a row is inserted into relay_deposits.
--   process_pending_filings() then checks filing_fee_reservations to compute
--   available balance and advances FIFO-ordered "Awaiting Funds" orders.

BEGIN;

-- Relay deposit notifications parsed from email
CREATE TABLE IF NOT EXISTS relay_deposits (
    id              SERIAL PRIMARY KEY,
    amount_cents    INTEGER NOT NULL,           -- deposited amount in cents
    sender_name     TEXT NOT NULL,              -- e.g. "FID BKG SVC LLC" for Stripe
    source          TEXT NOT NULL DEFAULT 'stripe',  -- 'stripe' | 'other'
    email_uid       TEXT NOT NULL UNIQUE,       -- IMAP UID to prevent duplicate processing
    email_subject   TEXT,
    detected_at     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    processed       BOOLEAN NOT NULL DEFAULT FALSE,
    processed_at    TIMESTAMPTZ
);

CREATE INDEX IF NOT EXISTS idx_relay_deposits_unprocessed
    ON relay_deposits (detected_at)
    WHERE processed = FALSE;

-- Filing fee reservations — tracks which deposits are committed to which orders
CREATE TABLE IF NOT EXISTS filing_fee_reservations (
    id              SERIAL PRIMARY KEY,
    order_id        TEXT NOT NULL,              -- e.g. "CRTC-2026-0001" or "FO-2026-0042"
    order_type      TEXT NOT NULL,              -- 'canada_crtc' | 'formation'
    amount_cents    INTEGER NOT NULL,           -- filing fee reserved (BC ~C$350 → USD, US state fee)
    -- Status lifecycle: pending → reserved → spent | released
    status          TEXT NOT NULL DEFAULT 'pending'
                    CHECK (status IN ('pending', 'reserved', 'spent', 'released')),
    relay_deposit_id INTEGER REFERENCES relay_deposits(id),
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    reserved_at     TIMESTAMPTZ,               -- when workflow advanced to Filing/Incorporation
    spent_at        TIMESTAMPTZ,               -- when Playwright confirmed card charged
    released_at     TIMESTAMPTZ,               -- if filing failed → funds returned to pool
    notes           TEXT
);

CREATE INDEX IF NOT EXISTS idx_filing_fee_reservations_status
    ON filing_fee_reservations (status, created_at);

CREATE INDEX IF NOT EXISTS idx_filing_fee_reservations_order
    ON filing_fee_reservations (order_id);

-- Helper view: current available balance in Relay filing account
-- available = sum(deposits) - sum(reserved + spent reservations)
CREATE OR REPLACE VIEW relay_available_balance AS
SELECT
    COALESCE((SELECT SUM(amount_cents) FROM relay_deposits), 0)
    - COALESCE((SELECT SUM(amount_cents) FROM filing_fee_reservations
                WHERE status IN ('reserved', 'spent')), 0)
    AS available_cents;

COMMIT;
