-- ==========================================================================
-- 老系统用户权限迁移前审计 SQL
-- 目标库：docauditai
-- 用途：在正式迁移 sso_users / roles / user_role / permissions / role_permissions / sys_routes / role_route 前，
--       先出质量统计，识别脏数据、空地区、无角色用户、历史脏角色。
-- ============================================================================

-- 1. 基础行数
SELECT 'sso_users' AS table_name, COUNT(*) AS total FROM sso_users
UNION ALL SELECT 'roles', COUNT(*) FROM roles
UNION ALL SELECT 'user_role', COUNT(*) FROM user_role
UNION ALL SELECT 'permissions', COUNT(*) FROM permissions
UNION ALL SELECT 'role_permissions', COUNT(*) FROM role_permissions
UNION ALL SELECT 'sys_routes', COUNT(*) FROM sys_routes
UNION ALL SELECT 'role_route', COUNT(*) FROM role_route;

-- 2. 用户地区分布
SELECT COALESCE(NULLIF(BTRIM(area), ''), '<EMPTY>') AS area_value, COUNT(*) AS user_count
FROM sso_users
GROUP BY 1
ORDER BY user_count DESC, area_value;

-- 3. 重复 sub
SELECT sub, COUNT(*) AS dup_count
FROM sso_users
GROUP BY sub
HAVING COUNT(*) > 1
ORDER BY dup_count DESC, sub;

-- 4. 重复 username
SELECT username, COUNT(*) AS dup_count
FROM sso_users
GROUP BY username
HAVING COUNT(*) > 1
ORDER BY dup_count DESC, username;

-- 5. 空地区 / 禁用 / 软删除 用户统计
SELECT
    COUNT(*) FILTER (WHERE area IS NULL OR BTRIM(area) = '') AS empty_area_count,
    COUNT(*) FILTER (WHERE status <> 0) AS disabled_count,
    COUNT(*) FILTER (WHERE deleted_at IS NOT NULL) AS deleted_count
FROM sso_users;

-- 6. 无角色用户
SELECT u.id, u.sub, u.username, u.nick_name, u.area
FROM sso_users u
LEFT JOIN user_role ur ON ur.user_id = u.id
WHERE ur.id IS NULL
ORDER BY u.id;

-- 7. 角色分布
SELECT r.role_key, r.role_name, COUNT(ur.user_id) AS user_count
FROM roles r
LEFT JOIN user_role ur ON ur.role_id = r.id
GROUP BY r.id, r.role_key, r.role_name
ORDER BY user_count DESC, r.role_key;

-- 8. 历史角色排查（重点看是否还有不应带入新系统的角色）
SELECT role_key, role_name, data_scope, description
FROM roles
ORDER BY role_key;

-- 9. user_role 脏引用
SELECT ur.*
FROM user_role ur
LEFT JOIN sso_users u ON u.id = ur.user_id
LEFT JOIN roles r ON r.id = ur.role_id
WHERE u.id IS NULL OR r.id IS NULL
ORDER BY ur.id;

-- 10. role_permissions 脏引用
SELECT rp.*
FROM role_permissions rp
LEFT JOIN roles r ON r.id = rp.role_id
LEFT JOIN permissions p ON p.id = rp.permission_id
WHERE r.id IS NULL OR p.id IS NULL
ORDER BY rp.id;

-- 11. role_route 脏引用
SELECT rr.*
FROM role_route rr
LEFT JOIN roles r ON r.id = rr.role_id
LEFT JOIN sys_routes sr ON sr.id = rr.route_id
WHERE r.id IS NULL OR sr.id IS NULL
ORDER BY rr.id;
