from __future__ import annotations

from datetime import datetime

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

from app.db.session import Base


class Product(Base):
    __tablename__ = "products"

    id: Mapped[int] = mapped_column(primary_key=True)
    tenant_id: Mapped[str] = mapped_column(String(64), default="default")
    client_name: Mapped[str] = mapped_column(String(255))
    item_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
    name: Mapped[str] = mapped_column(String(255), index=True)
    mix_id: Mapped[int] = mapped_column(ForeignKey("mixes.id"))
    sale_type: Mapped[str] = mapped_column(String(64), default="standard")
    own_bag: Mapped[bool] = mapped_column(Boolean, default=False)
    visible: Mapped[bool] = mapped_column(Boolean, default=True)
    unit_of_measure: Mapped[str] = mapped_column(String(64), default="20kg bag")
    items_per_pallet: Mapped[int] = mapped_column(Integer, default=50)
    bagging_process: Mapped[str | None] = mapped_column(String(64), nullable=True)
    distributor_margin: Mapped[float | None] = mapped_column(Float, nullable=True)
    wholesale_margin: Mapped[float | None] = mapped_column(Float, nullable=True)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

    mix: Mapped["Mix"] = relationship(back_populates="products")
    ingredients: Mapped[list["ProductIngredient"]] = relationship(
        back_populates="product",
        cascade="all, delete-orphan",
        order_by="ProductIngredient.sort_order",
    )


class ProductIngredient(Base):
    __tablename__ = "product_ingredients"
    __table_args__ = (UniqueConstraint("product_id", "raw_material_id", name="uq_product_ingredient"),)

    id: Mapped[int] = mapped_column(primary_key=True)
    tenant_id: Mapped[str] = mapped_column(String(64), default="default", index=True)
    product_id: Mapped[int] = mapped_column(ForeignKey("products.id"), index=True)
    raw_material_id: Mapped[int] = mapped_column(ForeignKey("raw_materials.id"), index=True)
    quantity_kg: Mapped[float] = mapped_column(Float)
    sort_order: Mapped[int] = mapped_column(Integer, default=0)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)

    product: Mapped[Product] = relationship(back_populates="ingredients")
    raw_material: Mapped["RawMaterial"] = relationship()


from app.models.mix import Mix  # noqa: E402
from app.models.raw_material import RawMaterial  # noqa: E402
