INSERT INTO platform_permission (permission_code, permission_name, module)
VALUES
    ('platform.session.read', '平台会话查看', 'platform'),
    ('platform.session.manage', '平台会话管理', 'platform')
ON DUPLICATE KEY UPDATE
    permission_name = VALUES(permission_name),
    module = VALUES(module);

SET @next_platform_role_permission_id = (SELECT IFNULL(MAX(id), 0) FROM platform_role_permission);
INSERT INTO platform_role_permission (id, role_id, permission_id)
SELECT
    (@next_platform_role_permission_id := @next_platform_role_permission_id + 1) AS id,
    1 AS role_id,
    p.id AS permission_id
FROM platform_permission p
WHERE p.permission_code = 'platform.session.read'
  AND NOT EXISTS (
    SELECT 1 FROM platform_role_permission rp WHERE rp.role_id = 1 AND rp.permission_id = p.id
  );

INSERT INTO platform_role_permission (id, role_id, permission_id)
SELECT
    (@next_platform_role_permission_id := @next_platform_role_permission_id + 1) AS id,
    1 AS role_id,
    p.id AS permission_id
FROM platform_permission p
WHERE p.permission_code = 'platform.session.manage'
  AND NOT EXISTS (
    SELECT 1 FROM platform_role_permission rp WHERE rp.role_id = 1 AND rp.permission_id = p.id
  );

INSERT INTO platform_menu (menu_code, menu_name, route_path, permission_code, sort_no, status, is_deleted, created_by, updated_by)
VALUES
    ('platform_auth_session_manage', '平台会话管理', '/platform/auth-sessions', 'platform.session.read', 20, 'ENABLED', 0, 0, 0)
ON DUPLICATE KEY UPDATE
    menu_name = VALUES(menu_name),
    route_path = VALUES(route_path),
    permission_code = VALUES(permission_code),
    sort_no = VALUES(sort_no),
    status = VALUES(status),
    is_deleted = VALUES(is_deleted),
    updated_at = CURRENT_TIMESTAMP;

SET @next_platform_role_menu_id = (SELECT IFNULL(MAX(id), 0) FROM platform_role_menu);
INSERT INTO platform_role_menu (id, role_id, menu_id)
SELECT
    (@next_platform_role_menu_id := @next_platform_role_menu_id + 1) AS id,
    1 AS role_id,
    m.id AS menu_id
FROM platform_menu m
WHERE m.menu_code = 'platform_auth_session_manage'
  AND NOT EXISTS (
    SELECT 1 FROM platform_role_menu rm WHERE rm.role_id = 1 AND rm.menu_id = m.id
  );
