from datetime import datetime

from sqlalchemy import BigInteger, Boolean, ForeignKey, Integer, String
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.models.base import BaseModel


class UserMembership(BaseModel):
    """用户会员信息表。记录用户当前的会员等级、积分、累计消费等。"""

    __tablename__ = "user_memberships"

    user_id: Mapped[int] = mapped_column(
        BigInteger,
        ForeignKey("users.id", ondelete="CASCADE"),
        nullable=False,
        unique=True,
        index=True,
        comment="用户ID",
    )

    member_level_id: Mapped[int | None] = mapped_column(
        Integer,
        ForeignKey("member_levels.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
        comment="当前会员等级ID",
    )
    member_level_locked: Mapped[bool] = mapped_column(
        Boolean, default=False, nullable=False, comment="是否锁定会员等级，锁定后不随累计消费自动调整"
    )
    agent_tier: Mapped[str | None] = mapped_column(
        String(32), nullable=True, index=True, comment="伙伴/代理档位：yunqi/yunxiang/yunce/yunling/yunzun/yunguan"
    )

    total_spent: Mapped[int] = mapped_column(
        Integer, default=0, nullable=False, comment="累计消费金额，单位分"
    )

    total_points: Mapped[int] = mapped_column(
        Integer, default=0, nullable=False, comment="累计获得积分"
    )

    available_points: Mapped[int] = mapped_column(
        Integer, default=0, nullable=False, comment="当前可用积分"
    )

    upgraded_at: Mapped[datetime | None] = mapped_column(
        nullable=True, comment="等级升级时间"
    )

    # 关系
    member_level: Mapped["MemberLevel"] = relationship("MemberLevel", lazy="joined")
