-- ============================================================
-- V4: Document hierarchy — chapter and section tables
-- Supports parent-child retrieval pattern for RAG precision.
-- ============================================================

CREATE TABLE IF NOT EXISTS chapter (
    id           VARCHAR(200) PRIMARY KEY,
    book_id      UUID NOT NULL REFERENCES book(id) ON DELETE CASCADE,
    number       INT NOT NULL DEFAULT 1,
    title        VARCHAR(500),
    page_start   INT,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS section (
    id           VARCHAR(200) PRIMARY KEY,
    chapter_id   VARCHAR(200) NOT NULL REFERENCES chapter(id) ON DELETE CASCADE,
    book_id      UUID NOT NULL REFERENCES book(id) ON DELETE CASCADE,
    number       VARCHAR(50),
    title        VARCHAR(500),
    page_start   INT NOT NULL,
    page_end     INT NOT NULL,
    full_text    TEXT NOT NULL,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_section_book    ON section(book_id);
CREATE INDEX IF NOT EXISTS idx_section_chapter ON section(chapter_id);
