"""优惠券积分商城领取记录表"""
import enum
from datetime import datetime

from sqlalchemy import BigInteger, DateTime, ForeignKey, Integer, String
from sqlalchemy import Enum as SAEnum
from sqlalchemy.orm import Mapped, mapped_column

from app.models.base import BaseModel


class CouponMallClaimStatus(str, enum.Enum):
    CLAIMED = "claimed"    # 已领取
    USED = "used"          # 已使用
    EXPIRED = "expired"    # 已过期


class CouponMallClaim(BaseModel):
    """用户从积分商城领取优惠券的记录。"""

    __tablename__ = "coupon_mall_claims"

    mall_item_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("coupon_mall_items.id", ondelete="CASCADE"), nullable=False, index=True,
    )
    promo_code_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("promo_codes.id", ondelete="CASCADE"), nullable=False, index=True,
    )
    user_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True,
    )
    # 领取时支付的积分
    points_paid: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    # 领取时生成的专属优惠码（商城领取时每个用户有一个独立 code）
    code: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    status: Mapped[CouponMallClaimStatus] = mapped_column(
        SAEnum(CouponMallClaimStatus, values_callable=lambda e: [m.value for m in e]),
        default=CouponMallClaimStatus.CLAIMED, nullable=False, index=True,
    )
    used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    order_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("orders.id", ondelete="SET NULL"), nullable=True, index=True,
    )
