BEGIN;

CREATE TABLE IF NOT EXISTS broker_callback_state (
    id TEXT PRIMARY KEY,
    state_hash TEXT NOT NULL UNIQUE,
    user_id TEXT NOT NULL REFERENCES app_user(id) ON DELETE CASCADE,
    session_id TEXT NOT NULL REFERENCES app_session(id) ON DELETE CASCADE,
    broker TEXT NOT NULL,
    flow TEXT NOT NULL,
    created_at TIMESTAMPTZ NOT NULL,
    expires_at TIMESTAMPTZ NOT NULL,
    consumed_at TIMESTAMPTZ
);

CREATE INDEX IF NOT EXISTS idx_broker_callback_state_lookup
    ON broker_callback_state (user_id, session_id, broker, flow, expires_at DESC);

COMMIT;
