-- 章节拆分为 chapter_sections：每段正文 + 配图独立存储，chapters 只保留封面图
-- 执行顺序: 1) 本文件  2) python -m scripts.migrate_chapters_to_sections
-- 执行方式: psql -U <user> -d <database> -f api/migrations/add_chapter_sections.sql

-- ========== 1. 新建 chapter_sections 表 ==========
CREATE TABLE IF NOT EXISTS chapter_sections (
    id VARCHAR NOT NULL PRIMARY KEY,
    chapter_id VARCHAR NOT NULL REFERENCES chapters(id) ON DELETE CASCADE,
    order_index INTEGER NOT NULL,
    content TEXT NOT NULL,
    image JSONB,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS ix_chapter_sections_chapter_id ON chapter_sections(chapter_id);
CREATE INDEX IF NOT EXISTS ix_chapter_sections_order ON chapter_sections(chapter_id, order_index);

-- ========== 2. chapters 表增加 cover_image ==========
DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'chapters' AND column_name = 'cover_image') THEN
        ALTER TABLE chapters ADD COLUMN cover_image JSONB;
        RAISE NOTICE '已添加 chapters.cover_image';
    END IF;
END $$;

-- ========== 3. 回填与删列由脚本 scripts.migrate_chapters_to_sections 完成 ==========
