from datetime import datetime
from decimal import Decimal
from sqlalchemy import BigInteger, Index, ForeignKey, DECIMAL
from sqlalchemy.dialects.mysql import DATETIME as MYSQL_DATETIME
from sqlalchemy.orm import Mapped, mapped_column
from app.core.models.base import Base, TenantMixin


class DiscountUsageLog(Base, TenantMixin):
    """促销使用记录

    每次成功核销写入一行，用于：
    - 校验每人使用次数（usage_limit_per_customer）
    - 后台查看促销使用明细
    - 订单取消时可按 order_id 删除对应记录
    """

    __tablename__ = "discount_usage_logs"
    __table_args__ = (
        Index("ix_usage_discount_customer", "discount_id", "customer_id"),
        Index("ix_usage_order", "order_id"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    discount_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("discounts.id", ondelete="CASCADE"), nullable=False
    )
    customer_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("customers.id", ondelete="CASCADE"), nullable=False
    )
    order_id: Mapped[int | None] = mapped_column(
        BigInteger, ForeignKey("orders.id", ondelete="SET NULL"), nullable=True, comment="关联订单，NULL = 预校验阶段"
    )
    discount_amount: Mapped[Decimal | None] = mapped_column(
        DECIMAL(12, 2), nullable=True,
        comment="本次该券的抵扣金额；NULL = 本列上线前的历史数据",
    )
    created_at: Mapped[datetime] = mapped_column(
        MYSQL_DATETIME(fsp=3), nullable=False,
        default=datetime.utcnow,
        comment="核销时间"
    )

    def __repr__(self) -> str:
        return f"<DiscountUsageLog discount={self.discount_id} customer={self.customer_id} order={self.order_id}>"
