-- # 书籍章节表
--
-- ## 基本信息
--
-- 模块：book
-- 表名：book_chapter
-- 模型：model/book/book_chapter.go
-- 迁移接入：initialize/gorm_biz.go
-- 删除策略：硬删表
-- 职责：承载书籍章节发布单元、章节文件地址和阅读锚点基础信息，保证同一本书内章节编号稳定且唯一。

CREATE TABLE book_chapter (
  id bigserial PRIMARY KEY,
  created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
  book_id bigint NOT NULL,
  title varchar(255) NOT NULL,
  chapter_no integer NOT NULL CHECK (chapter_no > 0),
  is_readable boolean NOT NULL DEFAULT false,
  content_file_url varchar(500) NOT NULL,
  total_lines integer NOT NULL DEFAULT 0 CHECK (total_lines >= 0),
  is_enabled boolean NOT NULL DEFAULT true,
  CHECK (NOT is_readable OR total_lines > 0)
);

COMMENT ON TABLE book_chapter IS '书籍章节表';
COMMENT ON COLUMN book_chapter.id IS '主键';
COMMENT ON COLUMN book_chapter.created_at IS '创建时间';
COMMENT ON COLUMN book_chapter.updated_at IS '更新时间';
COMMENT ON COLUMN book_chapter.book_id IS '所属书籍 ID';
COMMENT ON COLUMN book_chapter.title IS '章节标题';
COMMENT ON COLUMN book_chapter.chapter_no IS '同书内章节顺序编号';
COMMENT ON COLUMN book_chapter.is_readable IS '是否对 app 端开放阅读';
COMMENT ON COLUMN book_chapter.content_file_url IS '章节内容文件 URL';
COMMENT ON COLUMN book_chapter.total_lines IS '章节正文总行数';
COMMENT ON COLUMN book_chapter.is_enabled IS '章节是否启用';

CREATE UNIQUE INDEX uk_book_chapter_book_id_chapter_no ON book_chapter (book_id, chapter_no);
CREATE INDEX idx_book_chapter_book_id_is_enabled_is_readable ON book_chapter (book_id, is_enabled, is_readable);
CREATE INDEX idx_book_chapter_created_at ON book_chapter (created_at);
