-- Phase state machine gates: extend artifact phases to 5, add per-version
-- verdict, and a per-(requirement,phase) approved/current artifact pointer.

-- (1) 扩展产物阶段 CHECK，纳入 implementing/reviewing（审计报告/评审记录也是文档型产物）。
ALTER TABLE requirement_artifacts DROP CONSTRAINT requirement_artifacts_phase_check;
ALTER TABLE requirement_artifacts ADD CONSTRAINT requirement_artifacts_phase_check
  CHECK (phase IN ('planning','prototyping','auditing','implementing','reviewing'));

-- (2) 每版本评审结论。default 'none' 让现存行全部合法（无需数据迁移）。
-- 新列放在表末尾，满足 sqlc 列序约定（见 0012 注释）。
ALTER TABLE requirement_artifacts ADD COLUMN verdict TEXT NOT NULL DEFAULT 'none'
  CHECK (verdict IN ('none','pass','fail'));

-- (3) 每 (requirement, phase) 的"已批准/当前"产物指针。仅在首次批准后才有行。
CREATE TABLE requirement_phase_pointers (
  requirement_id       UUID NOT NULL REFERENCES requirements(id) ON DELETE CASCADE,
  phase                TEXT NOT NULL,
  approved_artifact_id UUID REFERENCES requirement_artifacts(id) ON DELETE SET NULL,
  approved_by          UUID REFERENCES users(id) ON DELETE SET NULL,
  approved_at          TIMESTAMPTZ,
  updated_at           TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (requirement_id, phase)
);
CREATE INDEX idx_req_phase_pointers_artifact ON requirement_phase_pointers(approved_artifact_id);
