export type PhoneResult =
  | { ok: true; e164: string; display: string }
  | { ok: false; code: "PHONE_INVALID" | "PHONE_SCIENTIFIC_NOTATION" | "REQUIRED" };

/** Ethiopian mobile: 09/07 local, 9/7 bare, +251/251 prefixed; spaces and dashes allowed. */
export function normalizePhone(raw: string): PhoneResult {
  const s = raw.trim();
  if (!s) return { ok: false, code: "REQUIRED" };
  if (/^\d+(\.\d+)?e\+?\d+$/i.test(s)) return { ok: false, code: "PHONE_SCIENTIFIC_NOTATION" };
  let d = s.replace(/[\s-]/g, "");
  if (d.startsWith("+")) d = d.slice(1);
  if (!/^\d+$/.test(d)) return { ok: false, code: "PHONE_INVALID" };
  if (d.startsWith("251")) d = d.slice(3);
  else if (d.startsWith("0")) d = d.slice(1);
  if (!/^[79]\d{8}$/.test(d)) return { ok: false, code: "PHONE_INVALID" };
  return { ok: true, e164: `+251${d}`, display: formatLocal(d) };
}
function formatLocal(nine: string) {
  const l = `0${nine}`;
  return `${l.slice(0, 4)} ${l.slice(4, 6)} ${l.slice(6, 8)} ${l.slice(8, 10)}`;
}
export function fmtPhone(e164OrLocal: string): string {
  const r = normalizePhone(e164OrLocal);
  return r.ok ? r.display : e164OrLocal;
}
