from sqlalchemy import Column, Integer, DateTime, Index, ForeignKey
from sqlalchemy.dialects.mysql import BIGINT
from sqlalchemy.orm import relationship
from app.core.time import now
from app.db.base import Base

class OrderItem(Base):
    __tablename__ = "order_items"
    __table_args__ = (
        Index("idx_order_product", "order_id", "product_id"),
    )

    id = Column(BIGINT(unsigned=True), primary_key=True, autoincrement=True)
    order_id = Column(BIGINT(unsigned=True), ForeignKey("orders.id"), nullable=False)
    product_id = Column(BIGINT(unsigned=True), ForeignKey("products.id"), nullable=False)
    quantity = Column(Integer, nullable=False)
    points_per_item = Column(Integer, nullable=False)
    total_points = Column(Integer, nullable=False)
    created_at = Column(DateTime, nullable=False, default=now)

    # This property allows retrieval of the associated order.
    order = relationship("Order", back_populates="items")
    # Add relationship to Product model
    product = relationship("Product")