from __future__ import annotations

from datetime import datetime

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

from app.db.session import Base


class Mix(Base):
    __tablename__ = "mixes"

    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))
    name: Mapped[str] = mapped_column(String(255), index=True)
    status: Mapped[str] = mapped_column(String(32), default="draft")
    version: Mapped[int] = mapped_column(default=1)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

    ingredients: Mapped[list["MixIngredient"]] = relationship(
        back_populates="mix",
        cascade="all, delete-orphan",
    )
    products: Mapped[list["Product"]] = relationship(back_populates="mix")


class MixIngredient(Base):
    __tablename__ = "mix_ingredients"
    __table_args__ = (UniqueConstraint("mix_id", "raw_material_id", name="uq_mix_ingredient"),)

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

    mix: Mapped[Mix] = relationship(back_populates="ingredients")
    raw_material: Mapped["RawMaterial"] = relationship()


from app.models.product import Product  # noqa: E402
from app.models.raw_material import RawMaterial  # noqa: E402
