const ROLE_PRIORITY = [
  ['admin', 'ادمین', 'مدیر سیستم'],
  ['ceo', 'مدیرعامل', 'مدیر عامل'],
  ['project_manager', 'مدیر پروژه'],
  ['product_manager', 'مدیر محصول'],
  ['scrum_master', 'اسکرام مستر'],
  ['specialist', 'team_member', 'کارشناس'],
  ['observer', 'ناظر'],
];

const normalizeRoleText = (value) => String(value || '').replace(/\s+/g, '').toLowerCase();

export const getUserRolePriority = (user) => {
  const roles = [user?.role, ...(user?.roles || [])].filter(Boolean);
  if (!roles.length) return ROLE_PRIORITY.length;

  const roleTexts = roles.flatMap((role) => [
    role.name,
    role.display_name,
  ]).map(normalizeRoleText);

  const priority = ROLE_PRIORITY.findIndex((aliases) => (
    aliases.some((alias) => roleTexts.includes(normalizeRoleText(alias)))
  ));

  return priority === -1 ? ROLE_PRIORITY.length : priority;
};

export const sortUsersByRolePriority = (users) => {
  return [...(users || [])].sort((a, b) => {
    const priorityDiff = getUserRolePriority(a) - getUserRolePriority(b);
    if (priorityDiff !== 0) return priorityDiff;
    return String(a?.name || '').localeCompare(String(b?.name || ''), 'fa');
  });
};
