-- Code index (pgvector RAG). Guarded CREATE EXTENSION so deployments without
-- superuser/owner privileges or without the pgvector image fail loudly here
-- (and the code degrades to keyword fallback when no embedding endpoint is set).
CREATE EXTENSION IF NOT EXISTS vector;

-- code_index_runs tracks one (workspace, commit, embedding_model) build attempt.
CREATE TABLE code_index_runs (
    id                    uuid PRIMARY KEY,
    workspace_id          uuid NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    worktree_id           uuid NULL REFERENCES workspace_worktrees(id) ON DELETE SET NULL,
    branch                text NOT NULL,
    commit_sha            text NOT NULL,
    status                text NOT NULL DEFAULT 'pending'
                              CHECK (status IN ('pending','running','completed','failed','stale')),
    embedding_endpoint_id uuid REFERENCES llm_endpoints(id),
    embedding_model       text NOT NULL,
    dims                  int NOT NULL,
    files_indexed         int NOT NULL DEFAULT 0,
    chunks_indexed        int NOT NULL DEFAULT 0,
    error                 text,
    started_at            timestamptz,
    finished_at           timestamptz,
    created_at            timestamptz NOT NULL DEFAULT now(),
    UNIQUE (workspace_id, commit_sha, embedding_model)
);

CREATE INDEX idx_code_index_runs_ws_status ON code_index_runs (workspace_id, status);

-- code_chunks stores embedded line-window chunks. The vector dimension is fixed
-- at migration time; one embedding model per deployment is enforced via config.
CREATE TABLE code_chunks (
    id           uuid PRIMARY KEY,
    run_id       uuid NOT NULL REFERENCES code_index_runs(id) ON DELETE CASCADE,
    workspace_id uuid NOT NULL,
    commit_sha   text NOT NULL,
    file_path    text NOT NULL,
    lang         text,
    start_line   int NOT NULL,
    end_line     int NOT NULL,
    content      text NOT NULL,
    content_sha  bytea NOT NULL,
    token_count  int,
    embedding    vector(1536) NOT NULL,
    created_at   timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX idx_code_chunks_embedding ON code_chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX idx_code_chunks_ws_commit ON code_chunks (workspace_id, commit_sha);
CREATE INDEX idx_code_chunks_file ON code_chunks (workspace_id, file_path);
