-- name: GetScope :one
SELECT id, name, abbreviation FROM scope
WHERE id = ?;

-- name: ListScopes :many
SELECT id, name, abbreviation FROM scope
ORDER BY name;

-- name: ListScopesByUser :many
SELECT id, s.name, abbreviation, sm.name as display_name FROM scope_member sm
RIGHT JOIN scope s on s.id = sm.scope_id
WHERE sm.user_id = ?
ORDER BY s.name;

-- name: ListScopeMembers :many
SELECT user_id, name, owner FROM scope_member
WHERE scope_id = ?
ORDER BY name;

-- name: GetScopeWithDisplayName :one
SELECT id, scope.name, abbreviation, sm.name AS display_name FROM scope
LEFT JOIN scope_member sm ON scope.id = sm.scope_id
WHERE id = ? AND sm.user_id = ?;

-- name: GetScopeDisplayName :one
SELECT name FROM scope_member
WHERE user_id = ? AND scope_id = ?;

-- name: InsertScope :execresult
INSERT INTO scope (id, name, abbreviation)
VALUES (?, ?, ?);

-- name: UpdateScope :exec
UPDATE scope SET name = ?, abbreviation = ? WHERE id = ?;

-- name: UpdateScopeMember :exec
REPLACE INTO scope_member (scope_id, user_id, name, owner)
VALUES (?, ?, ?, ?);

-- name: DeleteScopeMember :exec
DELETE FROM scope_member WHERE scope_id=? AND user_id=?;

-- name: DeleteAllScopeMembers :exec
DELETE FROM scope_member WHERE scope_id=?;

-- name: DeleteScope :exec
DELETE FROM scope WHERE id=?;
