-- 统一三阶段产物表：planning/prototyping/auditing 各自独立版本序列。
-- source_message_id 仅作"产物派生自哪条 chat 消息"的追溯，手填产物为 NULL。
CREATE TABLE requirement_artifacts (
  id                UUID PRIMARY KEY,
  requirement_id    UUID NOT NULL REFERENCES requirements(id) ON DELETE CASCADE,
  phase             TEXT NOT NULL CHECK (phase IN ('planning','prototyping','auditing')),
  version           INT  NOT NULL,
  content           TEXT NOT NULL,
  note              TEXT NOT NULL DEFAULT '',
  source_message_id BIGINT REFERENCES messages(id) ON DELETE SET NULL,
  created_by        UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
  created_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
  UNIQUE (requirement_id, phase, version)
);
CREATE INDEX idx_requirement_artifacts_req_phase ON requirement_artifacts(requirement_id, phase);

-- 旧 prototype 数据迁移（保留原 id/version/created_at）后下线旧表。
INSERT INTO requirement_artifacts
  (id, requirement_id, phase, version, content, note, source_message_id, created_by, created_at)
SELECT id, requirement_id, 'prototyping', version, content, note, NULL, created_by, created_at
FROM requirement_prototypes;
DROP TABLE requirement_prototypes;

-- 会话挂载 requirement（新列在表末尾，满足 sqlc 列序约定）。
ALTER TABLE conversations ADD COLUMN requirement_id UUID REFERENCES requirements(id);
CREATE INDEX conversations_requirement_idx ON conversations(requirement_id) WHERE requirement_id IS NOT NULL;
