-- # 用户阅读记录表
--
-- ## 基本信息
--
-- 模块：book
-- 表名：book_read_record
-- 模型：model/book/book_read_record.go
-- 迁移接入：initialize/gorm_biz.go
-- 删除策略：硬删表
-- 职责：承载用户按“用户+书籍”维度的最新阅读历史和续读锚点，支持阅读恢复与历史展示。

CREATE TABLE book_read_record (
  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,
  member_user_id bigint NOT NULL,
  book_id bigint NOT NULL,
  book_title_snapshot varchar(255) NOT NULL,
  read_progress numeric(5,2) NOT NULL DEFAULT 0.00 CHECK (read_progress >= 0 AND read_progress <= 100),
  chapter_id bigint NOT NULL CHECK (chapter_id > 0),
  line_index integer NOT NULL CHECK (line_index > 0),
  last_read_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP
);

COMMENT ON TABLE book_read_record IS '用户阅读记录表';
COMMENT ON COLUMN book_read_record.id IS '主键';
COMMENT ON COLUMN book_read_record.created_at IS '创建时间';
COMMENT ON COLUMN book_read_record.updated_at IS '更新时间';
COMMENT ON COLUMN book_read_record.member_user_id IS '阅读用户的会员 ID';
COMMENT ON COLUMN book_read_record.book_id IS '所属书籍 ID';
COMMENT ON COLUMN book_read_record.book_title_snapshot IS '阅读书籍标题快照';
COMMENT ON COLUMN book_read_record.read_progress IS '阅读进度百分比';
COMMENT ON COLUMN book_read_record.chapter_id IS '当前续读章节 ID';
COMMENT ON COLUMN book_read_record.line_index IS '当前续读文本行下标，正文首行为 1';
COMMENT ON COLUMN book_read_record.last_read_at IS '最近一次阅读时间';

CREATE UNIQUE INDEX uk_book_read_record_member_user_id_book_id ON book_read_record (member_user_id, book_id);
CREATE INDEX idx_book_read_record_member_user_id_last_read_at ON book_read_record (member_user_id, last_read_at);
CREATE INDEX idx_book_read_record_book_id ON book_read_record (book_id);
