-- name: InsertRun :one
INSERT INTO code_index_runs (
  id, workspace_id, worktree_id, branch, commit_sha, status,
  embedding_endpoint_id, embedding_model, dims
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING id, workspace_id, worktree_id, branch, commit_sha, status,
          embedding_endpoint_id, embedding_model, dims,
          files_indexed, chunks_indexed, error, started_at, finished_at, created_at;

-- name: GetRun :one
SELECT id, workspace_id, worktree_id, branch, commit_sha, status,
       embedding_endpoint_id, embedding_model, dims,
       files_indexed, chunks_indexed, error, started_at, finished_at, created_at
FROM code_index_runs
WHERE id = $1;

-- name: GetRunByCommit :one
SELECT id, workspace_id, worktree_id, branch, commit_sha, status,
       embedding_endpoint_id, embedding_model, dims,
       files_indexed, chunks_indexed, error, started_at, finished_at, created_at
FROM code_index_runs
WHERE workspace_id = $1 AND commit_sha = $2 AND embedding_model = $3;

-- name: GetLatestCompletedRun :one
SELECT id, workspace_id, worktree_id, branch, commit_sha, status,
       embedding_endpoint_id, embedding_model, dims,
       files_indexed, chunks_indexed, error, started_at, finished_at, created_at
FROM code_index_runs
WHERE workspace_id = $1 AND status = 'completed'
ORDER BY created_at DESC
LIMIT 1;

-- name: MarkRunRunning :exec
UPDATE code_index_runs
SET status = 'running', started_at = now()
WHERE id = $1;

-- name: MarkRunCompleted :exec
UPDATE code_index_runs
SET status = 'completed', files_indexed = $2, chunks_indexed = $3,
    error = NULL, finished_at = now()
WHERE id = $1;

-- name: MarkRunFailed :exec
UPDATE code_index_runs
SET status = 'failed', error = $2, finished_at = now()
WHERE id = $1;

-- name: MarkRunsStale :exec
UPDATE code_index_runs
SET status = 'stale'
WHERE workspace_id = $1 AND status IN ('pending','running','completed');

-- name: MarkStuckRunsStale :many
UPDATE code_index_runs
SET status = 'stale'
WHERE status = 'running' AND started_at < $1
RETURNING id;
