from typing import Optional
from sqlalchemy import BigInteger, ForeignKey, String, UniqueConstraint
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from core.database import Base
from api.v1.common.base_models import TenantScopedMixin, TimestampMixin
import enum

class OperationType(str, enum.Enum):
    IMP = "imp"  # Importación
    EXP = "exp"  # Exportación
    SM_IN = "sm_in"  # Entrada SM
    SM_OUT = "sm_out"  # Salida SM
    CTM_SEND = "ctm_send"  # Envío CTM
    CTM_RECEIVE = "ctm_receive"  # Recibo CTM

class InvoiceSettings(Base, TenantScopedMixin, TimestampMixin):
    __tablename__ = "invoice_settings"
    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "company_id",
            "invoice_type",
            "operation_type",
            name="uq_invoice_settings_tenant_company_type_op"
        ),
        {"schema": "a76"},
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)

    # Configuration Scope
    invoice_type: Mapped[str] = mapped_column(
        ForeignKey("public.invoice_types.key"),
        nullable=False
    )
    
    operation_type: Mapped[OperationType] = mapped_column(
        String(11),
        nullable=False
    )

    # The actual settings payload
    settings: Mapped[dict] = mapped_column(JSONB, nullable=False, default={})

    def __repr__(self):
        return f"<InvoiceSettings(id={self.id}, type={self.invoice_type}, op={self.operation_type})>"
