-- name: CreateSysMenu :one
INSERT INTO sys_menus (name, path, component, type, hidden, sort, status, parent_id, icon)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING id;

-- name: ListSysMenus :many
SELECT m.*, p.code AS permission_code
FROM sys_menus m
         LEFT JOIN sys_menu_permission mp ON m.id = mp.menu_id
         LEFT JOIN sys_permissions p ON mp.permission_id = p.id
ORDER BY m.id
LIMIT $1 OFFSET $2;

-- name: CountSysMenus :one
SELECT COUNT(*)
FROM sys_menus;

-- name: GetAllSysMenus :many
SELECT m.*,
       p.code AS permission_code
FROM sys_menus m
         LEFT JOIN sys_menu_permission mp ON m.id = mp.menu_id
         LEFT JOIN sys_permissions p ON p.id = mp.permission_id
ORDER BY m.sort ASC,
         m.id ASC;

-- name: GetSysMenuByID :one
SELECT *
FROM sys_menus
WHERE id = $1;

-- name: UpdateSysMenu :execrows
UPDATE sys_menus
SET name      = coalesce(sqlc.narg('name'), name),
    path      = coalesce(sqlc.narg('path'), path),
    component = coalesce(sqlc.narg('component'), component),
    type      = coalesce(sqlc.narg('type'), type),
    hidden    = coalesce(sqlc.narg('hidden'), hidden),
    sort      = coalesce(sqlc.narg('sort'), sort),
    status    = coalesce(sqlc.narg('status'), status),
    icon      = coalesce(sqlc.narg('icon'), status),
    parent_id = CASE WHEN @update_parent_id::boolean THEN @parent_id ELSE parent_id END
WHERE id = sqlc.arg('id');

-- name: DeleteSysMenu :execrows
DELETE
FROM sys_menus
WHERE id = $1;

-- name: CreateSysMenuPermission :exec
INSERT INTO sys_menu_permission (menu_id, permission_id)
VALUES ($1, $2);

-- name: DeleteSysMenuPermission :exec
DELETE
FROM sys_menu_permission
WHERE menu_id = $1;

-- name: DeleteSysPermissionByMenuID :exec
DELETE
FROM sys_permissions
WHERE id IN (SELECT permission_id
             FROM sys_menu_permission
             WHERE menu_id = $1);

-- name: UpdateSysMenuPermissionCode :exec
UPDATE sys_permissions p
SET code = coalesce(sqlc.narg('code'), code)
FROM sys_menu_permission mp
WHERE p.id = mp.permission_id
  AND mp.menu_id = $1;