import enum
from datetime import date
from decimal import Decimal

from sqlalchemy import Boolean, Date, ForeignKey, Numeric, String
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.models.base import Base, SoftDeleteMixin, TimestampMixin


class JenisProdukEnum(str, enum.Enum):
    gasoline = "gasoline"
    diesel = "diesel"


class Produk(Base, TimestampMixin, SoftDeleteMixin):
    __tablename__ = "master_produk"

    id: Mapped[int] = mapped_column(primary_key=True)
    nama: Mapped[str] = mapped_column(String(100))
    kode: Mapped[str] = mapped_column(String(20), unique=True, index=True)
    jenis: Mapped[JenisProdukEnum]
    is_subsidi: Mapped[bool] = mapped_column(Boolean, default=False)
    kuota_config: Mapped[dict | None] = mapped_column(JSONB, nullable=True)
    # Threshold: % of delivered volume where losses trigger a LOSSES_EXCEEDED anomaly
    losses_threshold_penerimaan_pct: Mapped[Decimal] = mapped_column(
        Numeric(6, 3), default=Decimal("0.150")
    )
    # Threshold: % of sold volume per shift/day/month where losses trigger a LOSSES_EXCEEDED anomaly
    losses_threshold_penjualan_pct: Mapped[Decimal] = mapped_column(
        Numeric(6, 3), default=Decimal("0.500")
    )
    is_active: Mapped[bool] = mapped_column(Boolean, default=True)

    harga_history: Mapped[list["ProdukHarga"]] = relationship(
        back_populates="produk",
        cascade="all, delete-orphan",
        order_by="ProdukHarga.berlaku_mulai.desc()",
    )


class ProdukHarga(Base):
    __tablename__ = "master_produk_harga"

    id: Mapped[int] = mapped_column(primary_key=True)
    produk_id: Mapped[int] = mapped_column(
        ForeignKey("master_produk.id", ondelete="CASCADE"), index=True
    )
    harga: Mapped[Decimal] = mapped_column(Numeric(15, 3))
    berlaku_mulai: Mapped[date] = mapped_column(Date, index=True)
    berlaku_sampai: Mapped[date | None] = mapped_column(Date, nullable=True)

    produk: Mapped["Produk"] = relationship(back_populates="harga_history")
