-- 217_document_lineage.sql
-- Phase 1A: AI 생성 문서가 어느 원본에서 파생됐는지 추적.
--
-- 이력 테이블 FK = ON DELETE RESTRICT (feedback_history_table_fk_restrict).
-- 부모 문서 hard delete 차단, soft delete (documents.deleted_at) 만 허용.

CREATE TABLE IF NOT EXISTS document_lineage (
    id                  BIGSERIAL PRIMARY KEY,
    source_document_id  BIGINT NOT NULL REFERENCES documents(id) ON DELETE RESTRICT,
    derived_document_id BIGINT NOT NULL REFERENCES documents(id) ON DELETE RESTRICT,
    relation_type       TEXT NOT NULL
        CHECK (relation_type IN ('cited','summarized_from','generated_from','revised_from')),
    metadata            JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at          TIMESTAMPTZ NOT NULL DEFAULT now(),
    CONSTRAINT document_lineage_no_self
        CHECK (source_document_id <> derived_document_id),
    CONSTRAINT document_lineage_uq
        UNIQUE (source_document_id, derived_document_id, relation_type)
);
