import type { Member } from './members';
import { generateUsernameFromName, normalizeUsername } from './members';

export interface AuthUser {
  id: string;
  name: string;
  username: string;
  roleId: string;
  departmentId: string;
  email: string;
}

export function toAuthUser(member: Member): AuthUser {
  return {
    id: member.id,
    name: member.name,
    username: normalizeUsername(member.username) || generateUsernameFromName(member.name, []),
    roleId: member.roleId,
    departmentId: member.departmentId,
    email: member.email,
  };
}

export function resolveAuthUserFromMembers(user: AuthUser, members: Member[]): AuthUser | null {
  const member = members.find((m) => m.id === user.id);
  return member ? toAuthUser(member) : null;
}

export function findMemberByUsernameCredentials(
  username: string,
  password: string,
  members: Member[],
): Member | null {
  const normalizedUsername = normalizeUsername(username);
  if (!normalizedUsername || !password) return null;
  return members.find((member) => (
    normalizeUsername(member.username) === normalizedUsername &&
    (member.password || 'Ftb@2024') === password
  )) ?? null;
}
