import type { RoleItem } from './members';
import { DEFAULT_ROLE_PERMISSIONS, DEFAULT_ROLE_PRESETS } from './permissions';

const XIAOBAO_WARNING_ROLE_PERMISSIONS: Record<string, string[]> = {
  'role-pm': ['xiaobao.warning:view', 'xiaobao.warning:manage'],
  'role-dev': ['xiaobao.warning:view'],
  'role-test': ['xiaobao.warning:view'],
  'role-design': ['xiaobao.warning:view'],
  'role-lead': ['xiaobao.warning:view'],
};

export function mergePresetRolePermissions(roles: RoleItem[]): { roles: RoleItem[]; changed: boolean } {
  let changed = false;
  const presetRoleIds = new Set(Object.keys(DEFAULT_ROLE_PERMISSIONS));
  const shouldEnsureNewPresets = roles.some((role) => presetRoleIds.has(role.id));
  const next = roles.map((role) => {
    const xiaobaoPermissions = XIAOBAO_WARNING_ROLE_PERMISSIONS[role.id];
    if (!xiaobaoPermissions || role.permissions.includes('*')) return role;
    const merged = Array.from(new Set([...role.permissions, ...xiaobaoPermissions]));
    if (merged.length === role.permissions.length) return role;
    changed = true;
    return { ...role, permissions: merged };
  });

  if (shouldEnsureNewPresets && !next.some((role) => role.id === 'role-lead')) {
    const groupLeader = DEFAULT_ROLE_PRESETS.find((role) => role.id === 'role-lead');
    if (groupLeader) {
      next.splice(Math.min(2, next.length), 0, groupLeader);
      changed = true;
    }
  }

  return { roles: next, changed };
}
