-- name: CreateSysRole :exec
INSERT INTO sys_roles (name, code, status)
VALUES ($1, $2, $3);

-- name: ListSysRoles :many
SELECT *
FROM sys_roles
ORDER BY id
LIMIT $1 OFFSET $2;

-- name: CountSysRoles :one
SELECT COUNT(*)
FROM sys_roles;

-- name: GetSysRoleByID :one
SELECT *
FROM sys_roles
WHERE id = $1;

-- name: ExistsSysRoleCode :one
SELECT EXISTS(SELECT 1
              FROM sys_roles
              WHERE code = sqlc.arg(code)
                AND (
                  sqlc.narg(id)::integer IS NULL
                      OR id <> sqlc.narg(id)::integer
                  ));

-- name: UpdateSysRole :execrows
UPDATE sys_roles
SET name   = coalesce(sqlc.narg('name'), name),
    status = coalesce(sqlc.narg('status'), status)
WHERE id = sqlc.arg('id');

-- name: DeleteSysRole :execrows
DELETE
FROM sys_roles
WHERE id = $1;

-- name: CreateSysRolePermission :copyfrom
INSERT INTO sys_role_permission (role_id, permission_id)
VALUES ($1, $2);

-- name: GetSysPermissionIdsByMenuIDs :many
SELECT permission_id
FROM sys_menu_permission
WHERE menu_id = ANY ($1::int[]);

-- name: GetSysPermissionIdsByApiIDs :many
SELECT permission_id
FROM sys_api_permission
WHERE api_id = ANY ($1::int[]);

-- name: GetAllSysRoles :many
SELECT *
from sys_roles;

-- name: GetSysRoleMenus :many
SELECT m.id, m.name
FROM sys_role_permission rp
         JOIN sys_menu_permission mp ON mp.permission_id = rp.permission_id
         JOIN sys_menus m ON m.id = mp.menu_id
WHERE rp.role_id = $1;

-- name: GetSysRoleApis :many
SELECT a.id, a."name"
FROM sys_role_permission rp
         JOIN sys_api_permission ap ON ap.permission_id = rp.permission_id
         JOIN sys_apis a ON a.id = ap.api_id
WHERE rp.role_id = $1;

-- name: DeleteSysRolePermissionByType :exec
DELETE
FROM sys_role_permission rp USING sys_permissions p
WHERE rp.permission_id = p.id
  AND rp.role_id = $1
  AND p."type" = $2;

-- name: DeleteSysRolePermissionByRoleID :exec
DELETE
FROM sys_role_permission
WHERE role_id = $1;

-- name: DeleteSysRolePermissionByPermissionID :exec
DELETE
FROM sys_role_permission
WHERE permission_id = $1;

-- name: DeleteSysUserRoleByRoleID :exec
DELETE
FROM sys_user_role
WHERE role_id = $1;