import { AppError } from './utils';

/** Normalize to E.164 (+639XXXXXXXXX) for Philippine mobiles. */
export function normalizePhilippinePhone(phone: string): string {
  let digits = phone.replace(/\D/g, '');

  if (digits.startsWith('63')) {
    digits = digits.slice(2);
  }
  if (digits.startsWith('0')) {
    digits = digits.slice(1);
  }

  if (!/^9\d{9}$/.test(digits)) {
    throw new AppError('Enter a valid 10-digit Philippine mobile number starting with 9', 400);
  }

  return `+63${digits}`;
}

/** Legacy phone formats that may exist in the database. */
export function philippinePhoneVariants(phone: string): string[] {
  const normalized = normalizePhilippinePhone(phone);
  const local = normalized.slice(3);
  return Array.from(
    new Set([normalized, `0${local}`, local, `63${local}`])
  );
}
