-- name: CreateSysMenu :one
INSERT INTO sys_menu (
    name, 
    display_name, 
    url, 
    type, 
    parent_id, 
    parent_path, 
    avatar, 
    style, 
    visible, 
    is_list, 
    status, 
    sort, 
    created_at, 
    updated_at
) VALUES (
    $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14
) RETURNING *;

-- name: UpdateSysMenu :one
UPDATE sys_menu
SET name         = $2,
    display_name = $3,
    url          = $4,
    type         = $5,
    parent_id    = $6,
    parent_path  = $7,
    avatar       = $8,
    style        = $9,
    visible      = $10,
    is_list      = $11,
    status       = $12,
    sort		     = $13,
    updated_at   = $14
WHERE id = $1
RETURNING *;

-- name: GetSysMenu :one
SELECT * FROM sys_menu
WHERE id = $1 LIMIT 1;

-- name: GetSysMenuByUrl :one
SELECT * FROM sys_menu
WHERE url = $1 LIMIT 1;

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

-- name: ListSysMenuByRoleID :many
SELECT * FROM sys_menu
WHERE id IN (SELECT menu_id
            FROM sys_role_menu
            WHERE role_id = $1);

-- name: ListSysMenuIDByRoleID :many
SELECT menu_id
FROM sys_role_menu
WHERE role_id = $1;

-- name: ExistsMenu :one
SELECT EXISTS (
    SELECT 1 FROM sys_menu
);

-- name: RecursiveSysMenus :many
WITH RECURSIVE dist AS (SELECT sys_menu.*
                        FROM sys_menu
                        WHERE status = 0
                          AND is_list = true
                        UNION ALL
                        SELECT sys_menu.*
                        FROM sys_menu,
                             dist
                        WHERE sys_menu.id = dist.parent_id)
SELECT *
FROM dist
ORDER BY dist.sort DESC, dist.id ASC;

-- name: RecursiveSysMenusByRoleID :many
WITH RECURSIVE dist AS (SELECT sys_menu.*
                        FROM sys_menu
                        WHERE status = 0
                          AND is_list = true
                          AND id IN (SELECT menu_id
                                     FROM sys_role_menu
                                     WHERE role_id = $1)
                        UNION ALL
                        SELECT sys_menu.*
                        FROM sys_menu,
                             dist
                        WHERE sys_menu.id = dist.parent_id)
SELECT *
FROM dist
ORDER BY dist.sort DESC, dist.id ASC;