/** Canonical Ethiopian mobile key (9 digits starting with 9) for duplicate checks. */
export function canonicalPhoneKey(v: unknown): string | null {
  const raw = String(v ?? "").trim();
  if (!raw) return null;
  let digits = raw.replace(/\D/g, "");
  if (!digits) return null;
  if (digits.startsWith("251") && digits.length >= 12) digits = digits.slice(-9);
  else if (digits.startsWith("251") && digits.length === 11) digits = digits.slice(-9);
  else if (digits.startsWith("0") && digits.length === 10) digits = digits.slice(1);
  if (digits.length === 9 && digits.startsWith("9")) return digits;
  return digits;
}

export function isScientificNotationPhone(v: unknown): boolean {
  const raw = String(v ?? "").trim();
  if (!raw) return false;
  return /^[+-]?\d+(\.\d+)?[eE][+-]?\d+$/.test(raw);
}

/** True when value is a valid Ethiopian mobile (9 digits starting with 9). */
export function isValidEthiopianMobilePhone(v: unknown): boolean {
  if (isScientificNotationPhone(v)) return false;
  const raw = String(v ?? "").trim();
  if (!raw) return false;
  if (/[a-df-zA-DF-Z]/.test(raw.replace(/^\+/, ""))) return false;
  const key = canonicalPhoneKey(v);
  return key !== null && key.length === 9 && key.startsWith("9") && /^\d{9}$/.test(key);
}

export function phonePrimaryValidationError(v: unknown): string | null {
  const raw = String(v ?? "").trim();
  if (!raw) return "Missing phonePrimary";
  if (isScientificNotationPhone(v)) {
    return "Invalid phonePrimary (scientific notation is not allowed; use a full mobile number)";
  }
  if (!isValidEthiopianMobilePhone(v)) {
    return "Invalid phonePrimary (must be a valid Ethiopian mobile number, e.g. 0911223344)";
  }
  return null;
}

/** Display/storage form: prefer canonical 9-digit mobile when recognized. */
export function normalizePhone(v: unknown): string {
  const key = canonicalPhoneKey(v);
  if (key && key.length === 9 && key.startsWith("9")) return key;
  return String(v ?? "").replace(/\s+/g, "").trim().toLowerCase();
}
