from __future__ import annotations

from datetime import date, datetime

from sqlalchemy import Date, DateTime, Float, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.db.session import Base


class RawMaterial(Base):
    __tablename__ = "raw_materials"

    id: Mapped[int] = mapped_column(primary_key=True)
    tenant_id: Mapped[str] = mapped_column(String(64), default="default")
    name: Mapped[str] = mapped_column(String(255), unique=True, index=True)
    supplier: Mapped[str | None] = mapped_column(String(255), nullable=True)
    unit_of_measure: Mapped[str] = mapped_column(String(64))
    kg_per_unit: Mapped[float] = mapped_column(Float)
    status: Mapped[str] = mapped_column(String(32), default="active")
    # Decimal places this ingredient's required-kg is rounded to in the mix
    # calculator output. Set per-ingredient from the Ingredients Editor.
    rounding_decimals: Mapped[int] = mapped_column(Integer, default=2)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

    price_versions: Mapped[list["RawMaterialPriceVersion"]] = relationship(
        back_populates="raw_material",
        cascade="all, delete-orphan",
        order_by="desc(RawMaterialPriceVersion.effective_date)",
    )


class RawMaterialPriceVersion(Base):
    __tablename__ = "raw_material_price_versions"

    id: Mapped[int] = mapped_column(primary_key=True)
    tenant_id: Mapped[str] = mapped_column(String(64), default="default")
    raw_material_id: Mapped[int] = mapped_column(ForeignKey("raw_materials.id"), index=True)
    market_value: Mapped[float] = mapped_column(Float)
    waste_percentage: Mapped[float] = mapped_column(Float, default=0.0)
    effective_date: Mapped[date] = mapped_column(Date, default=date.today)
    status: Mapped[str] = mapped_column(String(32), default="active")
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

    raw_material: Mapped[RawMaterial] = relationship(back_populates="price_versions")
