from sqlalchemy import (
    Column,
    String,
    Integer,
    JSON,
    DateTime,
    UniqueConstraint,
    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 Order(Base):
    __tablename__ = "orders"
    __table_args__ = (
        UniqueConstraint("order_number", name="uk_order_number"),
        Index("idx_status", "status"),
    )

    id = Column(BIGINT(unsigned=True), primary_key=True, autoincrement=True)
    user_id = Column(BIGINT(unsigned=True), ForeignKey("users.id"), nullable=False)
    order_number = Column(String(20), nullable=False)
    total_points = Column(Integer, nullable=False)
    shipping_details = Column(JSON, nullable=True)
    status = Column(String(20), nullable=False)
    address_id = Column(BIGINT(unsigned=True), ForeignKey("user_addresses.id", ondelete="SET NULL"), nullable=True)
    created_at = Column(DateTime, nullable=False, default=now)
    updated_at = Column(DateTime, nullable=False, default=now, onupdate=now)

    # This property allows retrieval of the associated order items.
    items = relationship("OrderItem", back_populates="order", cascade="all, delete-orphan")
    address = relationship("UserAddress", backref="orders")