-- V40: 修复V27简化权限越权问题 - 按最小权限原则重新分配
-- 问题：V27将所有简化权限(*:simple:*)批量授予所有角色，存在越权风险
-- 解决：移除所有简化权限，按PRD矩阵为执行层添加必要的简化权限

-- 1. 先删除所有角色的所有简化权限关联
DELETE FROM sys_role_permission
WHERE permission_id IN (SELECT id FROM sys_permission WHERE permission_code LIKE '%:simple:%');

-- 2. 为执行层角色添加必要的简化权限 (根据PRD矩阵)
-- 运营专员简化权限
INSERT INTO sys_role_permission (role_id, permission_id)
SELECT 10, id FROM sys_permission WHERE permission_code IN (
    'activity:simple:view', 'activity:simple:create', 'activity:simple:update',
    'reward:simple:view', 'dashboard:simple:view'
) AND NOT EXISTS (
    SELECT 1 FROM sys_role_permission WHERE role_id = 10 AND permission_id = id
);

-- 市场专员简化权限
INSERT INTO sys_role_permission (role_id, permission_id)
SELECT 11, id FROM sys_permission WHERE permission_code IN (
    'activity:simple:view', 'activity:simple:create', 'activity:simple:update',
    'dashboard:simple:view'
) AND NOT EXISTS (
    SELECT 1 FROM sys_role_permission WHERE role_id = 11 AND permission_id = id
);

-- 财务专员简化权限
INSERT INTO sys_role_permission (role_id, permission_id)
SELECT 12, id FROM sys_permission WHERE permission_code IN (
    'reward:simple:view', 'reward:simple:approve',
    'dashboard:simple:view'
) AND NOT EXISTS (
    SELECT 1 FROM sys_role_permission WHERE role_id = 12 AND permission_id = id
);

-- 风控专员简化权限
INSERT INTO sys_role_permission (role_id, permission_id)
SELECT 13, id FROM sys_permission WHERE permission_code IN (
    'risk:simple:view', 'risk:simple:audit', 'risk:simple:blacklist',
    'dashboard:simple:view'
) AND NOT EXISTS (
    SELECT 1 FROM sys_role_permission WHERE role_id = 13 AND permission_id = id
);

-- 客服专员简化权限
INSERT INTO sys_role_permission (role_id, permission_id)
SELECT 14, id FROM sys_permission WHERE permission_code IN (
    'user:simple:view', 'user:simple:update', 'user:simple:certify',
    'activity:simple:view',
    'dashboard:simple:view'
) AND NOT EXISTS (
    SELECT 1 FROM sys_role_permission WHERE role_id = 14 AND permission_id = id
);

-- 3. 为客服主管添加必要的简化权限
INSERT INTO sys_role_permission (role_id, permission_id)
SELECT 9, id FROM sys_permission WHERE permission_code IN (
    'user:simple:view', 'user:simple:update', 'user:simple:certify', 'user:simple:export',
    'activity:simple:view',
    'dashboard:simple:view', 'dashboard:simple:export'
) AND NOT EXISTS (
    SELECT 1 FROM sys_role_permission WHERE role_id = 9 AND permission_id = id
);

-- 4. 标记viewer角色为不可分配 (兼容保留但不推荐使用)
UPDATE sys_role SET status = 0 WHERE role_code = 'viewer';
