-- name: NextChangeRequestNumber :one
-- Per-project monotonic number; FOR UPDATE not needed because the
-- max(number)+1 INSERT runs inside the same tx, but we lock existing project
-- rows to serialize concurrent creates within a project.
SELECT COALESCE(MAX(number), 0) + 1 FROM change_requests WHERE project_id = $1 FOR UPDATE;

-- name: CreateChangeRequest :one
INSERT INTO change_requests (
  id, project_id, workspace_id, requirement_id, issue_id, number,
  title, description, source_branch, target_branch,
  state, review_verdict, ci_state, provider, external_id, external_url,
  merge_commit_sha, created_by
) VALUES (
  $1, $2, $3, $4, $5, $6,
  $7, $8, $9, $10,
  'open', 'pending', $11, $12, $13, $14,
  '', $15
)
RETURNING *;

-- name: GetChangeRequestByID :one
SELECT * FROM change_requests WHERE id = $1;

-- name: GetChangeRequestByNumber :one
SELECT cr.* FROM change_requests cr
JOIN projects p ON p.id = cr.project_id
WHERE p.slug = $1 AND cr.number = $2;

-- name: ListChangeRequestsByWorkspace :many
SELECT * FROM change_requests
WHERE workspace_id = $1
ORDER BY number DESC;

-- name: ListChangeRequestsByProject :many
SELECT * FROM change_requests
WHERE project_id = $1
ORDER BY number DESC;

-- name: UpdateChangeRequestReview :one
UPDATE change_requests
SET review_verdict = $2,
    reviewed_by    = $3,
    reviewed_at    = now(),
    updated_at     = now()
WHERE id = $1
RETURNING *;

-- name: UpdateChangeRequestState :one
UPDATE change_requests
SET state            = $2,
    merge_commit_sha = $3,
    merged_at        = $4,
    updated_at       = now()
WHERE id = $1
RETURNING *;

-- name: UpdateChangeRequestCI :one
UPDATE change_requests
SET ci_state   = $2,
    state      = $3,
    updated_at = now()
WHERE id = $1
RETURNING *;
