from decimal import Decimal
from typing import Optional

from api.v1.common.base_models import TenantScopedMixin, TimestampMixin
from core.database import Base
from sqlalchemy import Integer, Numeric, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column


class FractionRuleOctave(Base, TenantScopedMixin, TimestampMixin):
    """
    Fracciones por permiso de Regla Octava.
    Paridad: GFracROctava (Clarion SCAII).
    PK natural: (permission, line, fraction) — se usa junto a tenant/company.
    """

    __tablename__ = "fraction_rule_octave"
    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "company_id",
            "permission",
            "line",
            "fraction",
            name="uq_fraction_rule_octave_permission_line_fraction",
        ),
        {"schema": "a76"},
    )

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

    permission: Mapped[str] = mapped_column(String(20))                             # PERMISO
    line: Mapped[int] = mapped_column(Integer)                                      # LINEA
    fraction: Mapped[str] = mapped_column(String(10))                               # FRACCION
    quota_quantity: Mapped[Optional[Decimal]] = mapped_column(Numeric(19, 8))       # CANTIDADCUPO
    quantity_used: Mapped[Optional[Decimal]] = mapped_column(Numeric(23, 8))        # CANTUSADA
    quota_value: Mapped[Optional[Decimal]] = mapped_column(Numeric(23, 8))          # VALORCUPO
    value_used: Mapped[Optional[Decimal]] = mapped_column(Numeric(23, 8))           # VALORUSADA
    unit_cost_me: Mapped[Optional[Decimal]] = mapped_column(Numeric(23, 8))         # COSTOUNITARIOME
    unit_of_measure: Mapped[Optional[str]] = mapped_column(String(5))               # UNIMED
