"""
Modelo principal de Company
"""

from typing import Optional, TYPE_CHECKING
from sqlalchemy import Integer, String, SmallInteger, ForeignKey, Boolean
from sqlalchemy.orm import Mapped, mapped_column, relationship
from core.database import Base
from api.v1.common.base_models import TimestampMixin

if TYPE_CHECKING:
    from .submodels.address import CompanyAddress
    from .submodels.certification import CompanyCertification
    from .submodels.digital_certificate import CompanyDigitalCertificate
    from .submodels.vu import CompanyVU
    from .submodels.electronic_agent import CompanyElectronicAgent
    from .submodels.prevalidator import CompanyPrevalidator
    from .submodels.cfdi import CompanyCFDI


class Company(Base, TimestampMixin):
    """Información principal de la empresa"""

    __tablename__ = "company"
    __table_args__ = {"schema": "a76", "extend_existing": True}

    # Primary key
    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    tenant_id: Mapped[int] = mapped_column(
        ForeignKey("core.tenants.id"), nullable=False, index=True
    )

    # Información básica
    name: Mapped[Optional[str]] = mapped_column(String(256))
    rfc: Mapped[Optional[str]] = mapped_column(String(30))
    curp: Mapped[Optional[str]] = mapped_column(String(19))
    main_activity: Mapped[Optional[str]] = mapped_column(String(80))

    # Programa
    program: Mapped[Optional[str]] = mapped_column(String(7))
    program_number: Mapped[Optional[str]] = mapped_column(String(40))
    prosec: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
    prosec_authorization: Mapped[Optional[str]] = mapped_column(String(20))

    # Sectores
    sector1: Mapped[Optional[str]] = mapped_column(String(150))
    sector2: Mapped[Optional[str]] = mapped_column(String(150))
    sector3: Mapped[Optional[str]] = mapped_column(String(5))

    # Identificadores
    manufacturer_id: Mapped[Optional[str]] = mapped_column(String(25))
    broker_company: Mapped[Optional[str]] = mapped_column(String(6))

    # Responsable
    responsible: Mapped[Optional[str]] = mapped_column(String(80))
    responsible_name: Mapped[Optional[str]] = mapped_column(String(20))
    responsible_last_name: Mapped[Optional[str]] = mapped_column(String(20))
    responsible_mother_last_name: Mapped[Optional[str]] = mapped_column(String(20))
    responsible_rfc: Mapped[Optional[str]] = mapped_column(String(30))
    position: Mapped[Optional[str]] = mapped_column(String(30))

    # Configuración básica
    logo: Mapped[Optional[str]] = mapped_column(String(512))
    fiscal_deposit: Mapped[Optional[bool]] = mapped_column(Boolean, default=False, server_default="false")
    generate_barcodes_with_fiel: Mapped[Optional[bool]] = mapped_column(Boolean, default=False, server_default="false")
    order_format_type: Mapped[Optional[str]] = mapped_column(String(19))
    is_service_company: Mapped[Optional[bool]] = mapped_column(Boolean, default=False, server_default="false")
    client_name: Mapped[Optional[str]] = mapped_column(String(300))
    subassembly_mode: Mapped[Optional[str]] = mapped_column(String(7))

    # Configuraciones técnicas (flags)
    previous_code: Mapped[Optional[int]] = mapped_column(SmallInteger)
    active_labels: Mapped[Optional[int]] = mapped_column(SmallInteger)
    active_fractions: Mapped[Optional[int]] = mapped_column(SmallInteger)
    activate_caat: Mapped[Optional[int]] = mapped_column(SmallInteger)
    trans_interface: Mapped[Optional[int]] = mapped_column(SmallInteger)
    american_costs: Mapped[Optional[int]] = mapped_column(SmallInteger)
    scaf_readonly: Mapped[Optional[int]] = mapped_column(SmallInteger)
    parts_replacement: Mapped[Optional[int]] = mapped_column(SmallInteger)
    activate_facmexame: Mapped[Optional[int]] = mapped_column(SmallInteger)
    part_reference: Mapped[Optional[int]] = mapped_column(SmallInteger)    
    international_firm: Mapped[Optional[int]] = mapped_column(SmallInteger)
    seventh_amendment: Mapped[Optional[bool]] = mapped_column(
        Boolean
    )  # Septima enimenda (FinalContadorAElectronico)

    # Configuraciones simples
    ftp_key: Mapped[Optional[str]] = mapped_column(String(10))
    sifra_path: Mapped[Optional[str]] = mapped_column(String(255))
    version_type: Mapped[Optional[str]] = mapped_column(String(20))
    sql_language: Mapped[Optional[str]] = mapped_column(String(19))
    balance_operation_mode: Mapped[Optional[str]] = mapped_column(String(50))
    inter_db_name: Mapped[Optional[str]] = mapped_column(String(100))

    # ==================== RELACIONES CON SUBTABLAS ====================

    addresses: Mapped[list["CompanyAddress"]] = relationship(
        "CompanyAddress",
        back_populates="company",
        cascade="all, delete-orphan",
        lazy="selectin",
    )

    certification: Mapped[Optional["CompanyCertification"]] = relationship(
        "CompanyCertification",
        back_populates="company",
        uselist=False,
        cascade="all, delete-orphan",
        lazy="selectin",
    )

    digital_certificates: Mapped[list["CompanyDigitalCertificate"]] = relationship(
        "CompanyDigitalCertificate",
        back_populates="company",
        cascade="all, delete-orphan",
        lazy="selectin",
    )

    ventanilla_unica: Mapped[Optional["CompanyVU"]] = relationship(
        "CompanyVU",
        back_populates="company",
        uselist=False,
        cascade="all, delete-orphan",
        lazy="selectin",
    )

    electronic_agent: Mapped[Optional["CompanyElectronicAgent"]] = relationship(
        "CompanyElectronicAgent",
        back_populates="company",
        uselist=False,
        cascade="all, delete-orphan",
        lazy="selectin",
    )

    prevalidator: Mapped[Optional["CompanyPrevalidator"]] = relationship(
        "CompanyPrevalidator",
        back_populates="company",
        uselist=False,
        cascade="all, delete-orphan",
        lazy="selectin",
    )

    cfdi: Mapped[Optional["CompanyCFDI"]] = relationship(
        "CompanyCFDI",
        back_populates="company",
        uselist=False,
        cascade="all, delete-orphan",
        lazy="selectin",
    )
