CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE embedding_chunk
(
    id          UUID PRIMARY KEY,
    binary_id   UUID        NOT NULL REFERENCES binaries (id) ON DELETE CASCADE,
    chunk_type  VARCHAR(30) NOT NULL,
    source_type VARCHAR(30),
    source_id   UUID,
    content     TEXT        NOT NULL,
    embedding   vector(4096),
    metadata    JSONB,
    token_count INTEGER,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_embedding_chunk_binary ON embedding_chunk (binary_id);
CREATE INDEX idx_embedding_chunk_source ON embedding_chunk (source_type, source_id);

CREATE TABLE chat_session
(
    id         UUID PRIMARY KEY,
    binary_id  UUID         NOT NULL REFERENCES binaries (id) ON DELETE CASCADE,
    project_id UUID         NOT NULL REFERENCES projects (id) ON DELETE CASCADE,
    title      VARCHAR(255),
    chat_model VARCHAR(100) NOT NULL,
    created_at TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_chat_session_binary ON chat_session (binary_id);

CREATE TABLE chat_message
(
    id          UUID PRIMARY KEY,
    session_id  UUID        NOT NULL REFERENCES chat_session (id) ON DELETE CASCADE,
    role        VARCHAR(20) NOT NULL,
    content     TEXT        NOT NULL,
    token_count INTEGER,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_chat_message_session ON chat_message (session_id, created_at);
