# models/database/inventory.py

from sqlalchemy import Column, ForeignKey, Index, Integer, String, UniqueConstraint
from sqlalchemy.orm import relationship

from app.core.database import Base
from models.database.base import TimestampMixin


class Inventory(Base, TimestampMixin):
    __tablename__ = "inventory"

    id = Column(Integer, primary_key=True, index=True)
    product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
    vendor_id = Column(Integer, ForeignKey("vendors.id"), nullable=False, index=True)

    location = Column(String, nullable=False, index=True)
    quantity = Column(Integer, nullable=False, default=0)
    reserved_quantity = Column(Integer, default=0)

    # Optional: Keep GTIN for reference/reporting
    gtin = Column(String, index=True)

    # Relationships
    product = relationship("Product", back_populates="inventory_entries")
    vendor = relationship("Vendor")

    # Constraints
    __table_args__ = (
        UniqueConstraint(
            "product_id", "location", name="uq_inventory_product_location"
        ),
        Index("idx_inventory_vendor_product", "vendor_id", "product_id"),
        Index("idx_inventory_product_location", "product_id", "location"),
    )

    def __repr__(self):
        return f"<Inventory(product_id={self.product_id}, location='{self.location}', quantity={self.quantity})>"

    @property
    def available_quantity(self):
        """Calculate available quantity (total - reserved)."""
        return max(0, self.quantity - self.reserved_quantity)
