-- Enable pgvector extension
CREATE EXTENSION IF NOT EXISTS vector;

-- Table: indexed code chunks dari monorepo
CREATE TABLE IF NOT EXISTS code_chunks (
    id          BIGSERIAL PRIMARY KEY,
    repo        TEXT NOT NULL,                    -- nama repo/subproject, e.g. 'server-connection'
    file_path   TEXT NOT NULL,                    -- path relatif dari root monorepo
    language    TEXT,                             -- php, ts, tsx, py, md, dll
    start_line  INTEGER,
    end_line    INTEGER,
    content     TEXT NOT NULL,                    -- teks chunk asli
    embedding   vector(768),                      -- nomic-embed-text output
    indexed_at  TIMESTAMPTZ DEFAULT NOW(),
    checksum    TEXT                              -- MD5 file untuk deteksi perubahan
);

-- Table: user interaction memory
CREATE TABLE IF NOT EXISTS user_memory (
    id          BIGSERIAL PRIMARY KEY,
    username    TEXT NOT NULL,                    -- LDAP username
    pattern     TEXT NOT NULL,                    -- kategori: 'email_izin', 'coding_php', dll
    context     JSONB,                            -- detail konteks (atasan, gaya, dll)
    embedding   vector(768),                      -- embedding dari interaksi
    created_at  TIMESTAMPTZ DEFAULT NOW(),
    updated_at  TIMESTAMPTZ DEFAULT NOW()
);

-- Index HNSW untuk similarity search (lebih cepat dari IVFFlat)
CREATE INDEX IF NOT EXISTS code_chunks_embedding_idx
    ON code_chunks USING hnsw (embedding vector_cosine_ops)
    WITH (m = 16, ef_construction = 64);

CREATE INDEX IF NOT EXISTS user_memory_embedding_idx
    ON user_memory USING hnsw (embedding vector_cosine_ops)
    WITH (m = 16, ef_construction = 64);

-- Index biasa
CREATE INDEX IF NOT EXISTS code_chunks_repo_idx ON code_chunks (repo);
CREATE INDEX IF NOT EXISTS code_chunks_file_idx ON code_chunks (file_path);
CREATE INDEX IF NOT EXISTS user_memory_username_idx ON user_memory (username);
