"""商品评价模型
新增此文件后需运行: alembic revision --autogenerate -m "add_product_reviews"
"""
from sqlalchemy import BigInteger, String, Text, JSON, Integer, Index, ForeignKey
from sqlalchemy.dialects.mysql import TINYINT
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.core.models.base import Base, TimestampMixin, TenantMixin


class ProductReview(Base, TenantMixin, TimestampMixin):
    """商品评价"""

    __tablename__ = "product_reviews"
    __table_args__ = (
        Index("ix_review_product", "product_id"),
        Index("ix_review_customer", "customer_id"),
        Index("ix_review_status", "status"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id:          Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    product_id:  Mapped[int] = mapped_column(
        BigInteger, ForeignKey("products.id", ondelete="CASCADE"), nullable=False
    )
    customer_id: Mapped[int | None] = mapped_column(
        BigInteger, ForeignKey("customers.id", ondelete="SET NULL"), nullable=True, index=True
    )
    customer_name: Mapped[str] = mapped_column(String(100), nullable=False, default="匿名用户")
    rating:      Mapped[int]   = mapped_column(Integer, nullable=False, comment="1–5")
    content:     Mapped[str]   = mapped_column(Text, nullable=False)
    images:      Mapped[list | None] = mapped_column(JSON, nullable=True, comment="评价图片 URL 数组")
    variant:     Mapped[str | None]  = mapped_column(String(200), nullable=True, comment="购买规格，如 黑色/XL")
    status:      Mapped[str]  = mapped_column(
        String(20), nullable=False, default="pending",
        comment="pending / approved / hidden"
    )
    merchant_reply: Mapped[str | None] = mapped_column(Text, nullable=True, comment="商家回复")
    is_verified_purchase: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=0, comment="是否已购买核实")
    helpful_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment="有用数")

    def __repr__(self) -> str:
        return f"<ProductReview id={self.id} product_id={self.product_id} rating={self.rating}>"
