# app/modules/orders/models/customer_order_stats.py
"""
Customer order statistics model.

Tracks per-customer order aggregates (total orders, total spent, etc.)
owned by the orders module. This separates order stats from the
customer profile data owned by the customers module.
"""

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

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


class CustomerOrderStats(Base, TimestampMixin):
    """Aggregated order statistics per customer per store."""

    __tablename__ = "customer_order_stats"

    id = Column(Integer, primary_key=True, index=True)
    store_id = Column(
        Integer, ForeignKey("stores.id"), nullable=False, index=True
    )
    customer_id = Column(
        Integer, ForeignKey("customers.id"), nullable=False, index=True
    )
    total_orders = Column(Integer, nullable=False, default=0)
    total_spent_cents = Column(Integer, nullable=False, default=0)
    last_order_date = Column(DateTime(timezone=True), nullable=True)
    first_order_date = Column(DateTime(timezone=True), nullable=True)

    # Relationships
    store = relationship("Store")
    customer = relationship("Customer")

    __table_args__ = (
        UniqueConstraint(
            "store_id", "customer_id", name="uq_customer_order_stats_store_customer"
        ),
        Index("idx_customer_order_stats_customer", "customer_id"),
    )

    def __repr__(self):
        return (
            f"<CustomerOrderStats("
            f"store_id={self.store_id}, "
            f"customer_id={self.customer_id}, "
            f"total_orders={self.total_orders}, "
            f"total_spent_cents={self.total_spent_cents})>"
        )
