export interface TeacherCandidateRole {
  code?: string | null;
  name: string;
}

export interface TeacherCandidateUser {
  id: number;
  username: string;
  name?: string | null;
  isActive: boolean;
  isArchived: boolean;
  studentStatus?: string | null;
  roles?: TeacherCandidateRole[];
  profile?: { subjects?: string[] } | null;
}

const isSuperAdminRole = (role: TeacherCandidateRole) =>
  role.code === 'super_admin' || role.name === '超级管理员' || role.name === '超管';

export const isTeacherCandidate = (user: TeacherCandidateUser) => {
  if (!user.isActive || user.isArchived) return false;
  if (user.studentStatus && user.studentStatus !== 'staff') return false;
  return !(user.roles || []).some(isSuperAdminRole);
};

export const buildTeacherCandidateLabel = (user: TeacherCandidateUser) => {
  const displayName = user.name?.trim();
  const identity =
    displayName && displayName !== user.username
      ? `${displayName}（${user.username}）`
      : user.username;
  const roleNames = [...new Set((user.roles || []).map((role) => role.name).filter(Boolean))];
  const subjects = [
    ...new Set((user.profile?.subjects || []).map((subject) => subject.trim()).filter(Boolean)),
  ];

  return [identity, roleNames.join('/'), subjects.join('/')].filter(Boolean).join(' · ');
};

export const buildTeacherCandidateOptions = (users: TeacherCandidateUser[]) =>
  users.filter(isTeacherCandidate).map((user) => ({
    value: user.id,
    label: buildTeacherCandidateLabel(user),
  }));
