-- name: InsertTurn :one
INSERT INTO acp_turns (
  session_id, turn_index, prompt_request_id, status
) VALUES ($1, $2, $3, $4)
RETURNING id, session_id, turn_index, prompt_request_id, status,
          stop_reason, update_count, started_at, completed_at;

-- name: MarkTurnCompleted :exec
UPDATE acp_turns
SET status = 'completed', stop_reason = $3, update_count = $4, completed_at = now()
WHERE session_id = $1 AND turn_index = $2 AND status = 'in_progress';

-- name: MarkTurnAborted :exec
UPDATE acp_turns
SET status = 'aborted', completed_at = now()
WHERE session_id = $1 AND turn_index = $2 AND status = 'in_progress';

-- name: IncrementTurnUpdateCount :exec
UPDATE acp_turns
SET update_count = update_count + 1
WHERE session_id = $1 AND turn_index = $2 AND status = 'in_progress';

-- name: GetLatestTurnBySession :one
SELECT id, session_id, turn_index, prompt_request_id, status,
       stop_reason, update_count, started_at, completed_at
FROM acp_turns
WHERE session_id = $1
ORDER BY turn_index DESC
LIMIT 1;

-- name: ListTurnsBySession :many
SELECT id, session_id, turn_index, prompt_request_id, status,
       stop_reason, update_count, started_at, completed_at
FROM acp_turns
WHERE session_id = $1
ORDER BY turn_index ASC;

-- name: PurgeTurnsBefore :execrows
DELETE FROM acp_turns WHERE started_at < $1;
