INSERT INTO menu (tenant_id, menu_code, menu_name, route_path, permission_code, sort_no, status, is_deleted, created_by, updated_by)
VALUES
    (1, 'in_app_notification', '站内通知', '/in-app-notifications', 'notification.inapp.read', 181, '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_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,
    m.id
FROM role r
JOIN menu m ON m.tenant_id = r.tenant_id AND m.menu_code = 'in_app_notification' 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
  );
