# 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 datetime import date
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from beel_generated.models.create_invoice_request_lines_inner import CreateInvoiceRequestLinesInner
from beel_generated.models.invoice_processing_options import InvoiceProcessingOptions
from beel_generated.models.invoice_type import InvoiceType
from beel_generated.models.payment_info import PaymentInfo
from beel_generated.models.recipient import Recipient
from typing import Optional, Set
from typing_extensions import Self

class CreateInvoiceRequest(BaseModel):
    """
    CreateInvoiceRequest
    """ # noqa: E501
    type: InvoiceType
    series_id: Optional[StrictStr] = Field(default=None, description="Invoicing series ID (if not specified, uses default)")
    issue_date: date
    due_date: Optional[date] = Field(default=None, description="If not specified, calculated according to payment method")
    recipient: Recipient
    lines: Annotated[List[CreateInvoiceRequestLinesInner], Field(min_length=1)]
    payment_info: Optional[PaymentInfo] = None
    notes: Optional[Annotated[str, Field(strict=True, max_length=1000)]] = None
    rectified_invoice_id: Optional[StrictStr] = Field(default=None, description="Required if type is \"CORRECTIVE\"")
    rectification_reason: Optional[Annotated[str, Field(strict=True, max_length=500)]] = Field(default=None, description="Required if type is \"CORRECTIVE\"")
    metadata: Optional[Dict[str, Any]] = Field(default=None, description="Additional metadata in key-value format. Useful for storing references to external systems like Stripe, order IDs, etc. ")
    options: Optional[InvoiceProcessingOptions] = None
    __properties: ClassVar[List[str]] = ["type", "series_id", "issue_date", "due_date", "recipient", "lines", "payment_info", "notes", "rectified_invoice_id", "rectification_reason", "metadata", "options"]

    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 CreateInvoiceRequest 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 recipient
        if self.recipient:
            _dict['recipient'] = self.recipient.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in lines (list)
        _items = []
        if self.lines:
            for _item_lines in self.lines:
                if _item_lines:
                    _items.append(_item_lines.to_dict())
            _dict['lines'] = _items
        # override the default output from pydantic by calling `to_dict()` of payment_info
        if self.payment_info:
            _dict['payment_info'] = self.payment_info.to_dict()
        # override the default output from pydantic by calling `to_dict()` of options
        if self.options:
            _dict['options'] = self.options.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "type": obj.get("type"),
            "series_id": obj.get("series_id"),
            "issue_date": obj.get("issue_date"),
            "due_date": obj.get("due_date"),
            "recipient": Recipient.from_dict(obj["recipient"]) if obj.get("recipient") is not None else None,
            "lines": [CreateInvoiceRequestLinesInner.from_dict(_item) for _item in obj["lines"]] if obj.get("lines") is not None else None,
            "payment_info": PaymentInfo.from_dict(obj["payment_info"]) if obj.get("payment_info") is not None else None,
            "notes": obj.get("notes"),
            "rectified_invoice_id": obj.get("rectified_invoice_id"),
            "rectification_reason": obj.get("rectification_reason"),
            "metadata": obj.get("metadata"),
            "options": InvoiceProcessingOptions.from_dict(obj["options"]) if obj.get("options") is not None else None
        })
        return _obj


