# 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, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from beel_generated.models.customer import Customer
from beel_generated.models.customer_validation_error import CustomerValidationError
from beel_generated.models.customer_validation_warning import CustomerValidationWarning
from typing import Optional, Set
from typing_extensions import Self

class CustomerValidationItem(BaseModel):
    """
    Individual customer validation result. Works for bulk JSON, CSV import and Holded Excel import. 
    """ # noqa: E501
    index: StrictInt = Field(description="Customer index in the submitted list (0-based for bulk, 1-based for files). For CSV/Excel, represents the row number in the file. ")
    customer: Customer = Field(description="Parsed and validated customer. Can be null if there were critical parsing errors. ")
    status: StrictStr = Field(description="Customer validation status: - VALID: Completely valid customer - WARNING: Valid customer but with non-critical warnings - ERROR: Invalid customer, cannot be processed - DUPLICATE: Duplicate customer (in batch/CSV or database) - NIF_INVALID: NIF not valid according to AEAT census (VeriFactu) ")
    errors: List[CustomerValidationError] = Field(description="List of errors found (block import)")
    warnings: List[CustomerValidationWarning] = Field(description="List of warnings (do not block import)")
    row_number: Optional[StrictInt] = Field(default=None, description="Row number in the file (CSV or Excel depending on source_type)")
    __properties: ClassVar[List[str]] = ["index", "customer", "status", "errors", "warnings", "row_number"]

    @field_validator('status')
    def status_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['VALID', 'WARNING', 'ERROR', 'DUPLICATE', 'NIF_INVALID']):
            raise ValueError("must be one of enum values ('VALID', 'WARNING', 'ERROR', 'DUPLICATE', 'NIF_INVALID')")
        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 CustomerValidationItem 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 customer
        if self.customer:
            _dict['customer'] = self.customer.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in errors (list)
        _items = []
        if self.errors:
            for _item_errors in self.errors:
                if _item_errors:
                    _items.append(_item_errors.to_dict())
            _dict['errors'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in warnings (list)
        _items = []
        if self.warnings:
            for _item_warnings in self.warnings:
                if _item_warnings:
                    _items.append(_item_warnings.to_dict())
            _dict['warnings'] = _items
        # set to None if row_number (nullable) is None
        # and model_fields_set contains the field
        if self.row_number is None and "row_number" in self.model_fields_set:
            _dict['row_number'] = None

        return _dict

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

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

        _obj = cls.model_validate({
            "index": obj.get("index"),
            "customer": Customer.from_dict(obj["customer"]) if obj.get("customer") is not None else None,
            "status": obj.get("status"),
            "errors": [CustomerValidationError.from_dict(_item) for _item in obj["errors"]] if obj.get("errors") is not None else None,
            "warnings": [CustomerValidationWarning.from_dict(_item) for _item in obj["warnings"]] if obj.get("warnings") is not None else None,
            "row_number": obj.get("row_number")
        })
        return _obj


