"""CRM value objects."""

from __future__ import annotations

import re
from dataclasses import dataclass

from .exceptions import InvalidEmailError, InvalidLeadScoreError, InvalidPhoneError


_EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
_PHONE_PATTERN = re.compile(r"^\+?[0-9]{7,15}$")


@dataclass(frozen=True)
class EmailAddress:
    value: str

    def __post_init__(self) -> None:
        if not isinstance(self.value, str):
            raise InvalidEmailError("email must be a string")
        normalized = self.value.strip().lower()
        if not normalized or not _EMAIL_PATTERN.match(normalized):
            raise InvalidEmailError("email address is invalid")
        object.__setattr__(self, "value", normalized)


@dataclass(frozen=True)
class PhoneNumber:
    value: str

    def __post_init__(self) -> None:
        if not isinstance(self.value, str):
            raise InvalidPhoneError("phone must be a string")
        normalized = re.sub(r"[\s\-\(\)]", "", self.value.strip())
        if not normalized or not _PHONE_PATTERN.match(normalized):
            raise InvalidPhoneError("phone number is invalid")
        object.__setattr__(self, "value", normalized)


@dataclass(frozen=True)
class LeadScore:
    value: int

    def __post_init__(self) -> None:
        if isinstance(self.value, bool) or not isinstance(self.value, int):
            raise InvalidLeadScoreError("lead score must be an integer")
        if self.value < 0 or self.value > 100:
            raise InvalidLeadScoreError("lead score must be between 0 and 100")
