-- name: InsertRun :one
INSERT INTO orchestrator_runs (
  id, project_id, requirement_id, workspace_id, owner_id,
  status, current_phase, config, last_error
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING id, project_id, requirement_id, workspace_id, owner_id,
          status, current_phase, config, last_error,
          created_at, updated_at, ended_at;

-- name: GetRun :one
SELECT id, project_id, requirement_id, workspace_id, owner_id,
       status, current_phase, config, last_error,
       created_at, updated_at, ended_at
FROM orchestrator_runs
WHERE id = $1;

-- name: GetActiveRunByRequirement :one
SELECT id, project_id, requirement_id, workspace_id, owner_id,
       status, current_phase, config, last_error,
       created_at, updated_at, ended_at
FROM orchestrator_runs
WHERE requirement_id = $1
  AND status IN ('pending','running','paused')
ORDER BY created_at DESC
LIMIT 1;

-- name: ListRuns :many
SELECT id, project_id, requirement_id, workspace_id, owner_id,
       status, current_phase, config, last_error,
       created_at, updated_at, ended_at
FROM orchestrator_runs
WHERE ($1::uuid IS NULL OR project_id = $1)
  AND ($2::uuid IS NULL OR requirement_id = $2)
  AND ($3::text = '' OR status = $3)
ORDER BY created_at DESC
LIMIT $4;

-- name: UpdateRunStatus :one
UPDATE orchestrator_runs
SET status = $2,
    last_error = $3,
    ended_at = CASE WHEN $2 IN ('succeeded','failed','canceled') THEN now() ELSE ended_at END,
    updated_at = now()
WHERE id = $1
RETURNING id, project_id, requirement_id, workspace_id, owner_id,
          status, current_phase, config, last_error,
          created_at, updated_at, ended_at;

-- name: UpdateRunPhase :one
UPDATE orchestrator_runs
SET current_phase = $2,
    updated_at = now()
WHERE id = $1
RETURNING id, project_id, requirement_id, workspace_id, owner_id,
          status, current_phase, config, last_error,
          created_at, updated_at, ended_at;
