-- name: InsertSession :one
INSERT INTO acp_sessions (
  id, workspace_id, project_id, agent_kind_id, user_id,
  issue_id, requirement_id, branch, cwd_path, is_main_worktree, status
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
RETURNING id, workspace_id, project_id, agent_kind_id, user_id,
          issue_id, requirement_id, agent_session_id,
          branch, cwd_path, is_main_worktree, status,
          pid, exit_code, last_error, started_at, ended_at;

-- name: GetSessionByID :one
SELECT id, workspace_id, project_id, agent_kind_id, user_id,
       issue_id, requirement_id, agent_session_id,
       branch, cwd_path, is_main_worktree, status,
       pid, exit_code, last_error, started_at, ended_at
FROM acp_sessions
WHERE id = $1;

-- name: ListSessionsByUser :many
SELECT id, workspace_id, project_id, agent_kind_id, user_id,
       issue_id, requirement_id, agent_session_id,
       branch, cwd_path, is_main_worktree, status,
       pid, exit_code, last_error, started_at, ended_at
FROM acp_sessions
WHERE user_id = $1
  AND ($2::uuid IS NULL OR requirement_id = $2)
ORDER BY started_at DESC;

-- name: ListAllSessions :many
SELECT id, workspace_id, project_id, agent_kind_id, user_id,
       issue_id, requirement_id, agent_session_id,
       branch, cwd_path, is_main_worktree, status,
       pid, exit_code, last_error, started_at, ended_at
FROM acp_sessions
WHERE ($1::uuid IS NULL OR requirement_id = $1)
ORDER BY started_at DESC;

-- name: UpdateSessionRunning :exec
UPDATE acp_sessions
SET status = 'running', agent_session_id = $2, pid = $3
WHERE id = $1;

-- name: UpdateSessionFinished :exec
UPDATE acp_sessions
SET status = $2, exit_code = $3, last_error = $4, ended_at = now()
WHERE id = $1;

-- name: MarkSessionFailedIfActive :execrows
UPDATE acp_sessions
SET status = 'crashed', last_error = $2, ended_at = now()
WHERE id = $1 AND status IN ('starting', 'running');

-- name: CountActiveSessions :one
SELECT COUNT(*) FROM acp_sessions WHERE status IN ('starting', 'running');

-- name: CountActiveSessionsByUser :one
SELECT COUNT(*) FROM acp_sessions
WHERE user_id = $1 AND status IN ('starting', 'running');

-- name: ResetStuckSessionsOnRestart :many
UPDATE acp_sessions
SET status = 'crashed',
    last_error = 'process_aborted_on_restart',
    ended_at = now()
WHERE status IN ('starting', 'running')
RETURNING id, workspace_id, user_id, branch, agent_kind_id, is_main_worktree;

-- name: ReleaseMainWorktree :execrows
UPDATE workspaces SET active_main_session_id = NULL
WHERE id = $1 AND active_main_session_id = $2;

-- name: AcquireMainWorktree :execrows
UPDATE workspaces SET active_main_session_id = $1
WHERE id = $2 AND active_main_session_id IS NULL;
