-- 租户域恢复“专家列表”菜单，并为租户管理员补齐菜单与权限

SET @next_permission_id := (SELECT IFNULL(MAX(id), 0) + 1 FROM permission);
INSERT INTO permission (id, permission_code, permission_name, module)
SELECT @next_permission_id, 'expert.read', '查看专家列表', 'expert'
FROM dual
WHERE NOT EXISTS (SELECT 1 FROM permission WHERE permission_code = 'expert.read');

UPDATE permission
SET permission_name = '查看专家列表',
    module = 'expert'
WHERE permission_code = 'expert.read';

UPDATE menu
SET menu_name = '专家列表',
    route_path = '/experts',
    permission_code = 'expert.read',
    sort_no = 150,
    status = 'ENABLED',
    is_deleted = 0,
    updated_at = CURRENT_TIMESTAMP
WHERE menu_code = 'expert';

INSERT INTO menu (tenant_id, menu_code, menu_name, route_path, permission_code, sort_no, status, is_deleted, created_by, updated_by)
SELECT
    t.id,
    'expert',
    '专家列表',
    '/experts',
    'expert.read',
    150,
    'ENABLED',
    0,
    0,
    0
FROM tenant t
LEFT JOIN menu m ON m.tenant_id = t.id AND m.menu_code = 'expert'
WHERE t.is_deleted = 0
  AND m.id IS NULL;

SET @next_role_permission_id := (SELECT IFNULL(MAX(id), 0) FROM role_permission);
INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
SELECT
    (@next_role_permission_id := @next_role_permission_id + 1) AS id,
    r.tenant_id,
    r.id AS role_id,
    p.id AS permission_id
FROM role r
JOIN permission p ON p.permission_code = 'expert.read'
WHERE r.role_code = 'TENANT_ADMIN'
  AND r.is_deleted = 0
  AND NOT EXISTS (
    SELECT 1
    FROM role_permission rp
    WHERE rp.tenant_id = r.tenant_id
      AND rp.role_id = r.id
      AND rp.permission_id = p.id
  );

SET @next_role_menu_id := (SELECT IFNULL(MAX(id), 0) FROM role_menu);
INSERT INTO role_menu (id, tenant_id, role_id, menu_id)
SELECT
    (@next_role_menu_id := @next_role_menu_id + 1) AS id,
    r.tenant_id,
    r.id AS role_id,
    m.id AS menu_id
FROM role r
JOIN menu m ON m.tenant_id = r.tenant_id AND m.menu_code = 'expert' AND m.is_deleted = 0
WHERE r.role_code = 'TENANT_ADMIN'
  AND r.is_deleted = 0
  AND NOT EXISTS (
    SELECT 1
    FROM role_menu rm
    WHERE rm.tenant_id = r.tenant_id
      AND rm.role_id = r.id
      AND rm.menu_id = m.id
  );
