BEGIN;

CREATE TABLE IF NOT EXISTS execution_claim (
    id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL REFERENCES app_user(id) ON DELETE CASCADE,
    run_id TEXT NOT NULL REFERENCES strategy_run(run_id) ON DELETE CASCADE,
    mode TEXT NOT NULL,
    logical_time TIMESTAMPTZ NOT NULL,
    claimed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS uq_execution_claim_scope
    ON execution_claim (user_id, run_id, logical_time);

CREATE INDEX IF NOT EXISTS idx_execution_claim_run_claimed
    ON execution_claim (run_id, claimed_at DESC);

COMMIT;
