CREATE EXTENSION IF NOT EXISTS vector;

DROP TABLE IF EXISTS rag_chunk_embedding;

CREATE TABLE rag_chunk_embedding (
    id BIGSERIAL PRIMARY KEY,
    store_id BIGINT NOT NULL,
    document_id BIGINT NOT NULL,
    chunk_id BIGINT NOT NULL,
    embedding_model VARCHAR(100) NOT NULL,
    embedding_dimension INTEGER NOT NULL DEFAULT 1024,
    embedding VECTOR(1024) NOT NULL,
    content_hash VARCHAR(64),
    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_embedding_chunk_model UNIQUE (chunk_id, embedding_model),
    CONSTRAINT fk_rag_chunk_embedding_store_id FOREIGN KEY (store_id) REFERENCES rag_store (id),
    CONSTRAINT fk_rag_chunk_embedding_document_id FOREIGN KEY (document_id) REFERENCES rag_document (id),
    CONSTRAINT fk_rag_chunk_embedding_chunk_id FOREIGN KEY (chunk_id) REFERENCES rag_chunk (id)
);

CREATE INDEX idx_rag_chunk_embedding_store_id ON rag_chunk_embedding (store_id);
CREATE INDEX idx_rag_chunk_embedding_document_id ON rag_chunk_embedding (document_id);
CREATE INDEX idx_rag_chunk_embedding_chunk_id ON rag_chunk_embedding (chunk_id);
CREATE INDEX idx_rag_chunk_embedding_model ON rag_chunk_embedding (embedding_model);
CREATE INDEX idx_rag_chunk_embedding_enabled ON rag_chunk_embedding (enabled);
CREATE INDEX idx_rag_chunk_embedding_vector_hnsw
    ON rag_chunk_embedding USING hnsw (embedding vector_cosine_ops);

COMMENT ON TABLE rag_chunk_embedding IS 'RAG切片向量表';
COMMENT ON COLUMN rag_chunk_embedding.id IS 'ID';
COMMENT ON COLUMN rag_chunk_embedding.store_id IS '知识库ID';
COMMENT ON COLUMN rag_chunk_embedding.document_id IS '文档ID';
COMMENT ON COLUMN rag_chunk_embedding.chunk_id IS '切片ID';
COMMENT ON COLUMN rag_chunk_embedding.embedding_model IS '向量模型';
COMMENT ON COLUMN rag_chunk_embedding.embedding_dimension IS '向量维度';
COMMENT ON COLUMN rag_chunk_embedding.embedding IS '向量内容';
COMMENT ON COLUMN rag_chunk_embedding.content_hash IS '向量生成内容哈希';
COMMENT ON COLUMN rag_chunk_embedding.enabled IS '是否启用';
COMMENT ON COLUMN rag_chunk_embedding.version IS '版本';
COMMENT ON COLUMN rag_chunk_embedding.create_time IS '创建时间';
COMMENT ON COLUMN rag_chunk_embedding.update_time IS '更新时间';
COMMENT ON COLUMN rag_chunk_embedding.remark IS '备注';
COMMENT ON COLUMN rag_chunk_embedding.create_by IS '创建者';
COMMENT ON COLUMN rag_chunk_embedding.update_by IS '更新者';
