-- name: CreateSysRole :one
INSERT INTO sys_role (
    name,
    display_name,
    vip,
    parent_id,
    parent_path,
    status,
    sort,
    created_at,
    updated_at
) VALUES (
  $1, $2, $3, $4, $5, $6, $7, $8, $9
) RETURNING *;

-- name: UpdateSysRole :one
UPDATE sys_role
SET display_name = $2,
    status = $3, 
    parent_id = $4, 
    parent_path = $5, 
    sort = $6,  
    updated_at = $7
WHERE id = $1
RETURNING *;

-- name: GetSysRole :one
SELECT * FROM sys_role
WHERE id = $1 LIMIT 1;

-- name: CountSysRole :one
SELECT count(*) FROM sys_role
WHERE status = 0;

-- name: ListSysRole :many
SELECT * FROM sys_role
WHERE status = 0;

-- name: AllSysRole :many
SELECT * FROM sys_role
WHERE status = 0
ORDER BY sort DESC;

-- name: GetSysRoleByUserID :one
SELECT * FROM sys_role
WHERE id = (SELECT role_id
            FROM sys_user
            WHERE sys_user.id = $1);

-- name: ExistsVipRole :one
SELECT EXISTS (
    SELECT 1 FROM sys_role
    WHERE vip = true
);

-- name: GetFirstVipRole :one
SELECT * FROM sys_role
WHERE vip = true
ORDER BY id ASC
LIMIT 1;

-- name: CountSysRoleCondition :one
SELECT COUNT(*) FROM sys_role
WHERE (NOT @is_status::Boolean OR status = @status)
    AND (NOT @is_id::Boolean OR id = @id)
    AND (NOT @is_parent_id::Boolean OR parent_id = @parent_id)
    AND (@display_name::text = '' OR display_name ILIKE '%' || @display_name || '%');

-- name: ListSysRoleCondition :many
SELECT * FROM sys_role
WHERE (NOT @is_status::Boolean OR status = @status)
    AND (NOT @is_id::Boolean OR id = @id)
    AND (NOT @is_parent_id::Boolean OR parent_id = @parent_id)
    AND (@display_name::text = '' OR display_name ILIKE '%' || @display_name || '%')
ORDER BY created_at DESC
OFFSET @skip
LIMIT @size;