-- ──────────────────────────────────────────────────────────────────────────
-- Tracecoin wallet — full virtual-currency semantics
-- ──────────────────────────────────────────────────────────────────────────
-- Adds the safety machinery the wallet needs without putting a cap on
-- what users can buy or spend:
--
--   * Holds / escrow for pending actions (lead requests, contact
--     unlocks, AI credits, etc.). Holds have an explicit lifecycle
--     `ACTIVE → SETTLED / RELEASED / EXPIRED` and an optional
--     `expires_at` so the cron can auto-release them. This is what
--     prevents double-spending and spam without limiting purchases.
--   * Per-purchase bucket tracking (FIFO consumption, optional expiry).
--     Each row is one "bucket" of tracecoins the user bought. The
--     "first in, first out" rule means tracecoins purchased earlier
--     expire first if expiry is enabled.

-- 1. Per-purchase bucket tracking (FIFO consumption)
-- Each row is one "bucket" of tracecoins the user bought. amount_remaining
-- shrinks as the user spends; when it hits zero, the bucket is "drained"
-- and ignored by future spend operations. expires_at drives automatic
-- bucket-level expiry (NULL = no expiry for this bucket).
CREATE TABLE IF NOT EXISTS tracecoin_buckets (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    source VARCHAR(50) NOT NULL,
    amount INTEGER NOT NULL,
    amount_remaining INTEGER NOT NULL,
    reference_id UUID,
    source_kind VARCHAR(50) NOT NULL DEFAULT 'PURCHASE',
    expires_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CHECK (amount_remaining >= 0)
);
CREATE INDEX IF NOT EXISTS idx_tracecoin_buckets_user_expiry
    ON tracecoin_buckets(user_id, expires_at NULLS LAST, created_at);
CREATE UNIQUE INDEX IF NOT EXISTS uq_tracecoin_buckets_reference
    ON tracecoin_buckets(reference_id)
    WHERE reference_id IS NOT NULL;

-- 2. Holds / escrow for pending actions
-- ACTIVE: tracecoins are still on hold (subtracted from `available`)
-- SETTLED: the action completed and the hold was converted to a permanent
--          debit (a ledger row is written and linked)
-- RELEASED: the action was cancelled by the user or the system
-- EXPIRED: the hold passed `expires_at` and was auto-released by cron
CREATE TABLE IF NOT EXISTS tracecoin_holds (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    wallet_id UUID NOT NULL REFERENCES tracecoin_wallets(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    amount INTEGER NOT NULL CHECK (amount > 0),
    reason VARCHAR(100) NOT NULL,
    reference_id UUID,
    status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
    expires_at TIMESTAMPTZ,
    settled_at TIMESTAMPTZ,
    settled_ledger_id UUID REFERENCES tracecoin_ledger(id),
    released_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CHECK (status IN ('ACTIVE', 'SETTLED', 'RELEASED', 'EXPIRED'))
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_tracecoin_holds_reference
    ON tracecoin_holds(reference_id)
    WHERE reference_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_tracecoin_holds_user
    ON tracecoin_holds(user_id, status, expires_at);
