-- 角色路由权限数据插入脚本
-- 根据sys_routes_insert.sql中的路由数据和roles.sql中的角色数据进行关联

-- 清理现有数据（可选）
-- DELETE FROM role_route WHERE id > 0;

-- ----------------------------
-- 为admin角色分配全部路由权限  
-- ----------------------------
INSERT INTO role_route (role_id, route_id, permission) 
SELECT 1, id, 'RW' FROM sys_routes;

-- ----------------------------
-- 为common角色分配基础路由权限
-- ----------------------------
INSERT INTO role_route (role_id, route_id, permission) 
SELECT 2, id, 'RW' FROM sys_routes WHERE name IN (
  'home',
  'file-management', 'file-upload', 'documents',
  'rule-management', 'rule-groups', 'rules-list', 'rules-file',
  'contract-template', 'contract-search-ai', 'contract-list',
  'cross-checking'
) ON CONFLICT (role_id, route_id) DO NOTHING;

-- ----------------------------
-- 为deptLeader角色分配扩展权限
-- ----------------------------
INSERT INTO role_route (role_id, route_id, permission) 
SELECT 3, id, 'RW' FROM sys_routes WHERE name IN (
  'home',
  'chat-with-llm',
  'file-management', 'file-upload', 'documents',
  'rule-management', 'rule-groups', 'rules-list', 'rules-file',
  'contract-template', 'contract-search-ai', 'contract-list',
  'cross-checking'
) ON CONFLICT (role_id, route_id) DO NOTHING;

-- ----------------------------
-- 为groupLeader角色分配小组权限
-- ----------------------------
INSERT INTO role_route (role_id, route_id, permission) 
SELECT 4, id, 'RW' FROM sys_routes WHERE name IN (
  'home',
  'file-management', 'file-upload', 'documents',
  'rule-management', 'rule-groups', 'rules-list', 'rules-file',
  'contract-template', 'contract-search-ai', 'contract-list',
  'cross-checking'
) ON CONFLICT (role_id, route_id) DO NOTHING;

-- ----------------------------
-- 查询角色权限分配结果
-- ----------------------------
SELECT 
  r.role_name,
  sr.name as route_name,
  sr.path,
  sr.meta->>'title' as route_title,
  rr.permission
FROM role_route rr
JOIN roles r ON rr.role_id = r.id
JOIN sys_routes sr ON rr.route_id = sr.id
WHERE sr.parent_id = 0  -- 只显示一级菜单
ORDER BY r.id, (sr.meta->>'order')::int; 