-- Migration 021: Solver result cache table
--
-- Stores the latest solve/diagnose/kinematic result per item revision.
-- The UNIQUE constraint means re-running an operation overwrites the previous result.
-- See docs/SOLVER.md Section 9.

BEGIN;

CREATE TABLE solver_results (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    item_id         UUID NOT NULL REFERENCES items(id) ON DELETE CASCADE,
    revision_number INTEGER NOT NULL,
    job_id          UUID REFERENCES jobs(id) ON DELETE SET NULL,
    operation       TEXT NOT NULL,         -- 'solve', 'diagnose', 'kinematic'
    solver_name     TEXT NOT NULL,
    status          TEXT NOT NULL,         -- SolveStatus string ('Success', 'Failed', etc.)
    dof             INTEGER,
    diagnostics     JSONB DEFAULT '[]',
    placements      JSONB DEFAULT '[]',
    num_frames      INTEGER DEFAULT 0,
    solve_time_ms   DOUBLE PRECISION,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE(item_id, revision_number, operation)
);

CREATE INDEX idx_solver_results_item ON solver_results(item_id);
CREATE INDEX idx_solver_results_status ON solver_results(status);

COMMIT;
