-- =============================================
-- nginx配置管理平台 菜单 & 角色初始化 SQL
-- 系统编码: nginxServer
-- 执行位置: Mokee Gateway 数据库
-- =============================================

-- 0. 获取系统 ID
SET @system_id = (SELECT id FROM sys_system WHERE system_code = 'nginxServer' AND is_deleted = 0 LIMIT 1);

-- 1. 创建顶级菜单目录（用变量持有父菜单 UUID，子菜单直接引用）
SET @menu_nginx = REPLACE(UUID(),'-','');

INSERT INTO sys_menu (id, system_id, parent_id, menu_name, menu_path, component, icon, menu_type, sort_order, status) VALUES
(@menu_nginx, @system_id, '0', 'Nginx代理管理', '/nginx', 'Layout', 'Connection', 1, 1, 1);

-- 2. 创建子菜单（parent_id 直接用上面定义的变量）
INSERT INTO sys_menu (id, system_id, parent_id, menu_name, menu_path, component, icon, menu_type, sort_order, status) VALUES
(REPLACE(UUID(),'-',''), @system_id, @menu_nginx, 'Nginx转发管理', '/nginx-forwarding', 'views/NginxForwarding.vue', 'Connection', 2, 1, 1),
(REPLACE(UUID(),'-',''), @system_id, @menu_nginx, 'SSL证书管理', '/cert-management', 'views/CertManagement.vue', 'Key', 2, 2, 1),
(REPLACE(UUID(),'-',''), @system_id, @menu_nginx, 'DNS解析管理', '/dns-management', 'views/DnsManagement.vue', 'Link', 2, 3, 1);

-- 3. 创建角色（用变量持有角色 UUID）
SET @role_admin = REPLACE(UUID(),'-','');
SET @role_user  = REPLACE(UUID(),'-','');

INSERT INTO sys_role (id, system_id, role_name, role_code, description, status) VALUES
(@role_admin, @system_id, '管理员', 'admin', '拥有全部权限', 1),
(@role_user,  @system_id, '普通用户', 'user', '拥有基本权限', 1);

-- 4. 将本系统所有菜单分配给管理员角色
INSERT INTO sys_role_menu (id, role_id, menu_id)
SELECT REPLACE(UUID(),'-',''), @role_admin, m.id
FROM sys_menu m WHERE m.system_id = @system_id;

-- =============================================
-- 创建网关应用管理员账号
-- 角色: gateway-app-admin (只能看到自己绑定系统的数据)
-- =============================================

-- 5. 创建管理员用户（密码 admin123 的 BCrypt 密文，建议自行生成替换）
INSERT INTO sys_user (id, username, password, real_name, email, phone, status, is_deleted)
SELECT REPLACE(UUID(),'-',''), 'admin_nginxServer',
       '$2a$10$N.zmdr9k7uOCQb376NoUnuTJ8iAt6Z5EHsM8lE9lBOsl7iKTVKIUi',
       'Nginx配置管理平台管理员', 'admin@nginxServer.com', NULL, 1, 0
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM sys_user WHERE username = 'admin_nginxServer');

-- 6. 绑定管理员到 gateway 系统
INSERT INTO sys_user_system (id, user_id, system_id)
SELECT REPLACE(UUID(),'-',''), u.id, s.id
FROM sys_user u, sys_system s
WHERE u.username = 'admin_nginxServer'
  AND s.system_code = 'gateway'
  AND NOT EXISTS (
    SELECT 1 FROM sys_user_system us
    WHERE us.user_id = u.id AND us.system_id = s.id
  );

-- 7. 分配 gateway-app-admin 角色（gateway 系统下的应用管理员角色）
INSERT INTO sys_user_role (id, user_id, role_id)
SELECT REPLACE(UUID(),'-',''), u.id, r.id
FROM sys_user u, sys_role r, sys_system s
WHERE u.username = 'admin_nginxServer'
  AND r.role_code = 'gateway-app-admin'
  AND r.system_id = s.id
  AND s.system_code = 'gateway'
  AND NOT EXISTS (
    SELECT 1 FROM sys_user_role ur
    WHERE ur.user_id = u.id AND ur.role_id = r.id
  );
