DROP TABLE IF EXISTS rag_chunk;

CREATE TABLE rag_chunk (
    id BIGSERIAL PRIMARY KEY,
    store_id BIGINT NOT NULL,
    document_id BIGINT NOT NULL,
    chunk_index INTEGER NOT NULL,
    chunk_content TEXT NOT NULL,
    chunk_summary VARCHAR(1000) DEFAULT '',
    token_count INTEGER,
    page_number INTEGER,
    section_title VARCHAR(255) DEFAULT '',
    heading_path VARCHAR(1000) DEFAULT '',
    vector_id VARCHAR(128),
    metadata_json JSONB NOT NULL DEFAULT '{}'::jsonb,
    enabled BOOLEAN NOT NULL DEFAULT TRUE,
    version INTEGER NOT NULL DEFAULT 1,
    create_time TIMESTAMP,
    update_time TIMESTAMP,
    remark VARCHAR(500) DEFAULT '',
    create_by VARCHAR(64),
    update_by VARCHAR(64),
    CONSTRAINT uk_rag_chunk_document_index UNIQUE (document_id, chunk_index),
    CONSTRAINT fk_rag_chunk_store_id FOREIGN KEY (store_id) REFERENCES rag_store (id),
    CONSTRAINT fk_rag_chunk_document_id FOREIGN KEY (document_id) REFERENCES rag_document (id)
);

CREATE INDEX idx_rag_chunk_store_id ON rag_chunk (store_id);
CREATE INDEX idx_rag_chunk_document_id ON rag_chunk (document_id);
CREATE INDEX idx_rag_chunk_enabled ON rag_chunk (enabled);
CREATE INDEX idx_rag_chunk_vector_id ON rag_chunk (vector_id);
CREATE INDEX idx_rag_chunk_metadata_json ON rag_chunk USING GIN (metadata_json);

COMMENT ON TABLE rag_chunk IS 'RAG知识切片表';
COMMENT ON COLUMN rag_chunk.id IS 'ID';
COMMENT ON COLUMN rag_chunk.store_id IS '知识库ID';
COMMENT ON COLUMN rag_chunk.document_id IS '文档ID';
COMMENT ON COLUMN rag_chunk.chunk_index IS '文档内切片序号';
COMMENT ON COLUMN rag_chunk.chunk_content IS '切片内容';
COMMENT ON COLUMN rag_chunk.chunk_summary IS '切片摘要';
COMMENT ON COLUMN rag_chunk.token_count IS 'Token数量';
COMMENT ON COLUMN rag_chunk.page_number IS '页码';
COMMENT ON COLUMN rag_chunk.section_title IS '章节标题';
COMMENT ON COLUMN rag_chunk.heading_path IS '标题路径';
COMMENT ON COLUMN rag_chunk.vector_id IS '向量ID';
COMMENT ON COLUMN rag_chunk.metadata_json IS '切片级扩展元数据';
COMMENT ON COLUMN rag_chunk.enabled IS '是否启用';
COMMENT ON COLUMN rag_chunk.version IS '版本';
COMMENT ON COLUMN rag_chunk.create_time IS '创建时间';
COMMENT ON COLUMN rag_chunk.update_time IS '更新时间';
COMMENT ON COLUMN rag_chunk.remark IS '备注';
COMMENT ON COLUMN rag_chunk.create_by IS '创建者';
COMMENT ON COLUMN rag_chunk.update_by IS '更新者';
