-- 302_eid_review_set_draft.sql
-- 이드 복습세트 초안 (append-only derived-fact). 워커가 약점 스냅샷에서 권장 복습세트를 '제안'만 한다.
-- study overlay 항목6: "복습세트를 실제 복습 큐에 편성은 자율로 못 한다 — 초안만 제시, 사용자 1클릭".
-- 실제 편성(study_question_progress.due_at 편집)은 별도 T2 액션 — 이 draft 는 불변 제안 기록.
--
-- append-only 구조강제(=301 동일): actor·source_generated_at NOT NULL no-default(스탬프) + RULE(불변).
-- 상태전이 없음 — '현재 제안' = 최신 created_at. 새 제안은 supersedes_id 로 이전 것 가리킴(새 INSERT).
-- question_ids = ordered list[int] snapshot (study_quiz_sessions.question_ids 패턴, junction 안 씀).

CREATE TABLE IF NOT EXISTS eid_review_set_draft (
    id                   BIGSERIAL   PRIMARY KEY,
    user_id              BIGINT      NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    study_topic_id       BIGINT      REFERENCES study_topics(id) ON DELETE CASCADE,  -- nullable = cross-topic 세트
    question_ids         JSONB       NOT NULL,   -- ordered list[int]
    reason               VARCHAR(40) NOT NULL,   -- chronic | relapse | coverage | overdue
    actor                VARCHAR(20) NOT NULL,   -- 스탬프 = 'eid'
    source_weakness_id   BIGINT      REFERENCES eid_study_weakness(id) ON DELETE SET NULL,
    source_generated_at  TIMESTAMPTZ NOT NULL,   -- 스탬프
    supersedes_id        BIGINT      REFERENCES eid_review_set_draft(id) ON DELETE SET NULL,
    created_at           TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE OR REPLACE RULE eid_review_set_draft_no_update AS ON UPDATE TO eid_review_set_draft DO INSTEAD NOTHING;
CREATE OR REPLACE RULE eid_review_set_draft_no_delete AS ON DELETE TO eid_review_set_draft DO INSTEAD NOTHING;

CREATE INDEX IF NOT EXISTS idx_eid_review_draft_user ON eid_review_set_draft (user_id, created_at DESC);
