# coding: utf-8

"""
    BeeL Public API

    Public invoicing API for self-employed professionals in Spain with full VeriFactu support.  **Authentication:** This API uses **API Keys** for authentication. Endpoints are designed for external integrations, automation, and programmatic access.  For browser-based authentication, use the Private API (with Session Cookies).  **Key Features:** - VeriFactu regulatory compliance - Complete invoice management (standard, corrective, simplified) - Customer management - Tax and invoice series configuration - PDF generation - Email sending - Duplicate prevention (idempotency)  **Idempotency:** Creation endpoints (POST) support the `Idempotency-Key` header to prevent duplicates in case of retries.  **Identifiers:** - All resources use UUIDs for technical identification - Invoice numbers are human-readable and searchable 

    The version of the OpenAPI document: 1.0.0
    Contact: it@beel.es
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from beel_generated.models.address import Address
from beel_generated.models.recipient_data_alternative_id import RecipientDataAlternativeId
from typing import Optional, Set
from typing_extensions import Self

class RecipientData(BaseModel):
    """
    Recipient data in the invoice response. Note: For simplified invoices, only legal_name may be present. NIF and address are optional for SIMPLIFIED type invoices. 
    """ # noqa: E501
    customer_id: Optional[StrictStr] = Field(default=None, description="Customer UUID in the system (optional)")
    legal_name: Annotated[str, Field(min_length=1, strict=True, max_length=255)] = Field(description="Recipient legal name")
    trade_name: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=255)]] = Field(default=None, description="Recipient trade name (optional)")
    nif: Optional[Annotated[str, Field(min_length=9, strict=True, max_length=9)]] = Field(default=None, description="Spanish Tax ID (9 alphanumeric characters). Optional for simplified invoices (SIMPLIFIED type). Valid formats: - DNI: 8 digits + letter (e.g., 12345678A) - NIE: X/Y/Z + 7 digits + letter (e.g., X1234567A) - CIF: Letter + 7 digits + digit/letter (e.g., B12345678) ")
    alternative_id: Optional[RecipientDataAlternativeId] = None
    address: Optional[Address] = Field(default=None, description="Address (optional for simplified invoices)")
    phone: Optional[Annotated[str, Field(min_length=9, strict=True, max_length=20)]] = Field(default=None, description="Phone number. Allows digits, spaces, dashes, parentheses, and optional leading +")
    email: Optional[Annotated[str, Field(min_length=5, strict=True, max_length=255)]] = Field(default=None, description="Email address (minimum valid email is 5 chars, e.g. a@b.co)")
    __properties: ClassVar[List[str]] = ["customer_id", "legal_name", "trade_name", "nif", "alternative_id", "address", "phone", "email"]

    @field_validator('nif')
    def nif_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(r"^[A-Za-z0-9]{9}$", value):
            raise ValueError(r"must validate the regular expression /^[A-Za-z0-9]{9}$/")
        return value

    @field_validator('phone')
    def phone_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(r"^[+]?[0-9\s\-\(\)]+$", value):
            raise ValueError(r"must validate the regular expression /^[+]?[0-9\s\-\(\)]+$/")
        return value

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of RecipientData from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of alternative_id
        if self.alternative_id:
            _dict['alternative_id'] = self.alternative_id.to_dict()
        # override the default output from pydantic by calling `to_dict()` of address
        if self.address:
            _dict['address'] = self.address.to_dict()
        # set to None if customer_id (nullable) is None
        # and model_fields_set contains the field
        if self.customer_id is None and "customer_id" in self.model_fields_set:
            _dict['customer_id'] = None

        # set to None if trade_name (nullable) is None
        # and model_fields_set contains the field
        if self.trade_name is None and "trade_name" in self.model_fields_set:
            _dict['trade_name'] = None

        # set to None if nif (nullable) is None
        # and model_fields_set contains the field
        if self.nif is None and "nif" in self.model_fields_set:
            _dict['nif'] = None

        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of RecipientData from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate({
            "customer_id": obj.get("customer_id"),
            "legal_name": obj.get("legal_name"),
            "trade_name": obj.get("trade_name"),
            "nif": obj.get("nif"),
            "alternative_id": RecipientDataAlternativeId.from_dict(obj["alternative_id"]) if obj.get("alternative_id") is not None else None,
            "address": Address.from_dict(obj["address"]) if obj.get("address") is not None else None,
            "phone": obj.get("phone"),
            "email": obj.get("email")
        })
        return _obj


