import type { ARCAEmail } from "../types";
interface SelectedEmail {
  email: string;
  type: string;
}

const EMAIL_PRIORITY: Record<string, number> = {
  comercial: 3,
  personal: 2,
  tributario: 1,
};
export function isValidEmail(email: string): boolean {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return emailRegex.test(email);
}
export const getBestEmail = (emails: ARCAEmail[]): SelectedEmail => {
  if (!emails.length)
    return {
      email: "",
      type: "",
    };

  if (emails.length === 1) {
    return {
      email: emails[0].direccion,
      type: emails[0].tipoEmail,
    };
  }

  let bestEmail: ARCAEmail = emails[0];
  let bestRank = -1;

  for (const currentEmail of emails) {
    const normalizedType = currentEmail.tipoEmail.toLowerCase();
    const normalizedStatus = currentEmail.estado.toLowerCase();

    const typePriority = EMAIL_PRIORITY[normalizedType] ?? 0;

    const isConfirmed = normalizedStatus === "confirmado";

    /**
     * Ranking final:
     *
     * comercial confirmado -> 6
     * comercial -> 5
     * personal confirmado -> 4
     * personal -> 3
     * tributario confirmado -> 2
     * tributario -> 1
     * confirmado desconocido -> 0
     * desconocido -> -1
     */

    let rank = typePriority * 2;

    if (!isConfirmed) {
      rank -= 1;
    }

    // Si ya encontré un comercial confirmado, termino la búsqueda
    if (rank === 6)
      return {
        email: currentEmail.direccion,
        type: currentEmail.tipoEmail,
      };

    if (rank > bestRank) {
      bestRank = rank;
      bestEmail = currentEmail;
    }
  }

  return {
    email: bestEmail.direccion,
    type: bestEmail.tipoEmail,
  };
};
