-- Per-account payment risk: the loss and abuse signal an external/admin refund leaves
-- behind when the refunded chips were already spent. A refund revokes chips best-effort
-- and never drives a balance negative (D27, balances_chips_chk); the unrecoverable
-- remainder is a recorded loss and flips an abuse flag the /_gm financial report reads
-- (D40, E7). Mutable per-account state (upserted on each such refund), so — unlike the
-- ledger — it carries no append-only trigger. Additive: a new table only, so goose
-- applies it forward with no rewrite of existing data (the contour is not wiped). The
-- payments role inherits ALL on it via the schema default privileges set in 00010.
-- +goose Up

CREATE TABLE payments.account_risk (
    account_id uuid NOT NULL,
    -- abuse flips true the first time a refund cannot fully reclaim its chips (spent).
    abuse boolean DEFAULT false NOT NULL,
    -- loss_chips accumulates the unrecoverable chips across such refunds (bigint: an
    -- accumulator, mapped to int64 by go-jet — not the numeric->float64 trap).
    loss_chips bigint DEFAULT 0 NOT NULL,
    updated_at timestamp with time zone DEFAULT now() NOT NULL,
    CONSTRAINT account_risk_pkey PRIMARY KEY (account_id),
    CONSTRAINT account_risk_loss_chips_chk CHECK ((loss_chips >= 0))
);

-- +goose Down

DROP TABLE IF EXISTS payments.account_risk;
