import { isValidPhoneNumber, parsePhoneNumber } from 'libphonenumber-js';

export class PhoneNumberValidationError extends Error {
  constructor(public readonly originalInput: string) {
    super(
      `Invalid E.164 phone number format: ${originalInput}. Expected format: +[country code][number] (e.g., +14155552671)`
    );
    this.name = 'PhoneNumberValidationError';
  }
}

export function validatePhoneNumber(phoneNumber: string): string {
  const trimmed = phoneNumber.trim();

  if (!isValidPhoneNumber(trimmed)) {
    throw new PhoneNumberValidationError(phoneNumber);
  }

  const parsed = parsePhoneNumber(trimmed);
  if (!parsed || !parsed.number) {
    throw new PhoneNumberValidationError(phoneNumber);
  }

  return parsed.number;
}
