import re

from pydantic import EmailStr, TypeAdapter, ValidationError

EMAIL_ADAPTER = TypeAdapter(EmailStr)
PHONE_ALLOWED_CHARACTERS = re.compile(r"^[\d\s()+\-./]+$")


def normalize_customer_phone(value: str) -> str:
    cleaned = value.strip()
    if not cleaned:
        raise ValueError("Inserisci un numero di telefono valido.")
    if not PHONE_ALLOWED_CHARACTERS.fullmatch(cleaned):
        raise ValueError("Inserisci un numero di telefono valido.")

    has_plus_prefix = cleaned.startswith("+")
    digits = "".join(character for character in cleaned if character.isdigit())
    if len(digits) < 8 or len(digits) > 15:
        raise ValueError("Inserisci un numero di telefono valido.")
    return f"+{digits}" if has_plus_prefix else digits


def normalize_optional_customer_email(value: str | None) -> str | None:
    cleaned = (value or "").strip()
    if not cleaned:
        return None
    try:
        return str(EMAIL_ADAPTER.validate_python(cleaned))
    except ValidationError as exc:
        raise ValueError("Inserisci un indirizzo email valido.") from exc
