from sqlalchemy import BigInteger, ForeignKey, Integer, Numeric, String, Boolean
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.types import JSON

from app.models.base import BaseModel


class CartItem(BaseModel):
    """购物车项。一个用户可能有多条记录，每条对应一次"立即购买"快照。

    保存了下单瞬间的产品、价格、配置和系统镜像，避免后续 SKU/价格变更影响已选购的项目。
    """

    __tablename__ = "cart_items"

    user_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
    )
    product_id: Mapped[int] = mapped_column(
        ForeignKey("products.id", ondelete="CASCADE"), nullable=False, index=True
    )
    cycle: Mapped[str] = mapped_column(String(16), nullable=False, comment="计费周期：monthly / annually …")
    quantity: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
    auto_renew: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    alias: Mapped[str | None] = mapped_column(String(64), nullable=True, comment="主机别名")
    os_image: Mapped[str | None] = mapped_column(String(128), nullable=True, comment="所选系统镜像 label")

    # 价格快照（元）
    unit_price: Mapped[float] = mapped_column(Numeric(10, 2), nullable=False, comment="单台规格费用")
    addon_price: Mapped[float] = mapped_column(
        Numeric(10, 2), default=0, nullable=False, comment="单台扩展配置费用"
    )
    setup_fee: Mapped[float] = mapped_column(
        Numeric(10, 2), default=0, nullable=False, comment="一次性安装费"
    )

    # 配置选择快照（slider 等用户选项）
    slider_values: Mapped[dict | None] = mapped_column(JSON, nullable=True)
