-- name: ListProjects :many
SELECT * FROM project WHERE scope_id = ? ORDER BY status, name;

-- name: GetProject :one
SELECT * FROM project WHERE id = ? AND scope_id = ?;

-- name: InsertProject :execresult
INSERT INTO project (scope_id, owner_id, name, status, description)
VALUES (?, ?, ?, ?, ?);

-- name: UpdateProject :exec
UPDATE project
SET owner_id = ?,
    name = ?,
    status = ?,
    description = ?
WHERE id = ? AND scope_id = ?;

-- name: DeleteProject :exec
DELETE FROM project WHERE id = ? AND scope_id = ?;

-- name: ListProjectRequirements :many
SELECT * FROM project_requirement WHERE project_id = ?;

-- name: InsertProjectRequirement :execresult
INSERT INTO project_requirement (scope_id, project_id, name, status, description, is_coarse, aggregate_required)
VALUES (?, ?, ?, ?, ?, ?, ?);

-- name: UpdateProjectRequirement :exec
UPDATE project_requirement
SET name = ?,
    status = ?,
    description = ?,
    is_coarse = ?,
    aggregate_required = ?,
    project_id = ?
WHERE id = ? AND scope_id = ?;

-- name: DeleteProjectRequirement :exec
DELETE FROM project_requirement WHERE id = ? AND scope_id = ?;

-- name: DeleteAllProjectRequirements :exec
DELETE FROM project_requirement WHERE project_id = ?;

-- name: ClearItemProjectRequirement :exec
UPDATE item
SET project_requirement_id = NULL
WHERE project_requirement_id = ?;

-- name: ListProjectRequirementsStats :many
SELECT prs.* FROM project_requirement pr
RIGHT JOIN project_requirement_stat prs ON pr.id = prs.project_requirement_id
WHERE pr.project_id = ?;

-- name: ReplaceProjectRequirementStat :exec
REPLACE INTO project_requirement_stat (project_requirement_id, stat_id, required)
VALUES (?, ?, ?);

-- name: DeleteProjectRequirementStat :exec
DELETE FROM project_requirement_stat WHERE project_requirement_id = ? AND stat_id = ?;

-- name: DeleteAllProjectRequirementStats :exec
DELETE FROM project_requirement_stat WHERE project_requirement_id = ?;

-- name: ClearProjectRequirementStatsByStat :exec
DELETE FROM project_requirement_stat WHERE stat_id = ?;

-- name: DeleteAllScopeProjects :exec
DELETE FROM project WHERE scope_id = ?;

-- name: DeleteAllScopeProjectRequirements :exec
DELETE FROM project_requirement WHERE scope_id = ?;