/**
 * Phone normalisation for the admin login identifier (PLANNING.md §8).
 *
 * `admin_users.phone` stores E.164 (the lookup key); `phone_display` keeps the
 * value as the admin typed it, for the UI. Without normalisation `012-345 6789`
 * and `+60123456789` would become two accounts.
 *
 * Default region is Malaysia — every admin is local. `libphonenumber-js` is pure
 * JS (PLANNING.md §2), no native build.
 */
import { parsePhoneNumberFromString } from 'libphonenumber-js';
import { AppError } from './AppError';

const DEFAULT_REGION = 'MY';

export interface NormalizedPhone {
  /** E.164, e.g. "+60123456789" — stored in `admin_users.phone`. */
  e164: string;
  /** The input as typed (trimmed) — stored in `admin_users.phone_display`. */
  display: string;
}

export function normalizePhone(input: string): NormalizedPhone {
  const display = input.trim();
  const parsed = parsePhoneNumberFromString(display, DEFAULT_REGION);
  if (!parsed || !parsed.isValid()) {
    throw AppError.badRequest('Invalid phone number');
  }
  return { e164: parsed.number, display };
}
