from decimal import Decimal
from typing import Optional

from sqlalchemy import Integer, Numeric, PrimaryKeyConstraint, String
from sqlalchemy.orm import Mapped, mapped_column

from api.v1.common.base_models import TenantScopedMixin, TimestampMixin
from core.database import Base


class OctaveBalance(Base, TenantScopedMixin, TimestampMixin):
    """
    Saldos de Regla Octava por factura/partida.
    Paridad: SSaldosReglaOctava (Clarion SCAII).

    La PK es compuesta natural, igual que ROctSal_PKFaParPaiTiSeROProSisLin.
    Se agregan tenant_id y company_id al inicio para el scope multi-tenant.
    """

    __tablename__ = "octave_balance"
    __table_args__ = (
        PrimaryKeyConstraint(
            "tenant_id",
            "company_id",
            "invoice_import",
            "part_number",
            "origin_country",
            "fraction_type",
            "sector",
            "octave_permit",
            "origin",
            "system",
            "line",
            name="pk_octave_balance",
        ),
        {"schema": "a76"},
    )

    # ── PK compuesta ──────────────────────────────────────────────────────────
    invoice_import: Mapped[str] = mapped_column(String(15))   # FACTURAIMPO
    part_number: Mapped[str] = mapped_column(String(70))      # NUMPARTE
    origin_country: Mapped[str] = mapped_column(String(3))    # PAISORIGEN
    fraction_type: Mapped[str] = mapped_column(String(7))     # TIPOFRACIMPO
    sector: Mapped[str] = mapped_column(String(8))            # SECTOR
    octave_permit: Mapped[str] = mapped_column(String(100))    # PERMISOROCTAVA
    origin: Mapped[str] = mapped_column(String(3))            # PROCEDENCIA  ('TEM')
    system: Mapped[str] = mapped_column(String(5))            # SISTEMA      ('fixed_asset | inventory')
    line: Mapped[int] = mapped_column(Integer)                # LINEA

    # ── Datos ─────────────────────────────────────────────────────────────────
    quantity_stock: Mapped[Optional[Decimal]] = mapped_column(Numeric(19, 8))  # CANTEXITENCIA
    unit_of_measure: Mapped[Optional[str]] = mapped_column(String(5))          # UNIMED
    class_code: Mapped[Optional[str]] = mapped_column(String(8))               # CLASE
    import_fraction: Mapped[Optional[str]] = mapped_column(String(10))         # FRACCIONIMPO
    ro_fraction: Mapped[Optional[str]] = mapped_column(String(10))             # FRACCIONROCTAVA
    value_me: Mapped[Optional[Decimal]] = mapped_column(Numeric(23, 8))        # VALORME
