const PHONE_ALLOWED_CHARACTERS = /^[\d\s()+\-./]+$/;
const SIMPLE_EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export function normalizeCustomerPhone(value: string): string {
  const cleaned = value.trim();
  if (!cleaned || !PHONE_ALLOWED_CHARACTERS.test(cleaned)) {
    throw new Error("Inserisci un numero di telefono valido.");
  }

  const hasPlusPrefix = cleaned.startsWith("+");
  const digits = cleaned.replace(/\D/g, "");
  if (digits.length < 8 || digits.length > 15) {
    throw new Error("Inserisci un numero di telefono valido.");
  }

  return hasPlusPrefix ? `+${digits}` : digits;
}

export function normalizeOptionalCustomerEmail(value: string): string | null {
  const cleaned = value.trim();
  if (!cleaned) {
    return null;
  }
  if (!SIMPLE_EMAIL_PATTERN.test(cleaned)) {
    throw new Error("Inserisci un indirizzo email valido.");
  }
  return cleaned;
}

export function validateReservationContactForm(payload: {
  customerPhone: string;
  customerEmail: string;
}): {
  customerPhone: string;
  customerEmail: string | null;
} {
  return {
    customerPhone: normalizeCustomerPhone(payload.customerPhone),
    customerEmail: normalizeOptionalCustomerEmail(payload.customerEmail),
  };
}
