-- name: list-roles
SELECT id,
       name,
       description,
       permissions,
       created_at,
       updated_at
FROM roles
ORDER BY name;


-- name: get-role-by-id^
SELECT id,
       name,
       description,
       permissions,
       created_at,
       updated_at
FROM roles
WHERE id = :role_id
LIMIT 1;


-- name: create-role^
INSERT INTO roles (name, description, permissions)
VALUES (:name, :description, :permissions)
RETURNING id,
          name,
          description,
          permissions,
          created_at,
          updated_at;


-- name: update-role^
UPDATE roles
SET name = COALESCE(:name, name),
    description = COALESCE(:description, description),
    permissions = COALESCE(:permissions, permissions)
WHERE id = :role_id
RETURNING id,
          name,
          description,
          permissions,
          created_at,
          updated_at;


-- name: delete-role!
DELETE FROM roles
WHERE id = :role_id;


-- name: get-roles-for-user
SELECT r.id,
       r.name,
       r.description,
       r.permissions,
       r.created_at,
       r.updated_at
FROM roles r
JOIN user_roles ur ON ur.role_id = r.id
WHERE ur.user_id = :user_id
ORDER BY r.name;


-- name: assign-role-to-user!
INSERT INTO user_roles (user_id, role_id)
VALUES (:user_id, :role_id)
ON CONFLICT DO NOTHING;


-- name: revoke-role-from-user!
DELETE FROM user_roles
WHERE user_id = :user_id
  AND role_id = :role_id;


-- name: user-has-role^
SELECT EXISTS (
  SELECT 1
  FROM user_roles ur
  JOIN roles r ON r.id = ur.role_id
  WHERE ur.user_id = :user_id
    AND r.name = :role_name
) AS has_role;
