from sqlalchemy import BigInteger, Integer, String, Text, UniqueConstraint, Index
from sqlalchemy.dialects.mysql import TINYINT
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.models.base import Base, TenantMixin, TimestampMixin


class Brand(Base, TenantMixin, TimestampMixin):
    """商品品牌（用于筛选、SEO 聚合页和信任背书）"""

    __tablename__ = "brands"
    __table_args__ = (
        UniqueConstraint("tenant_id", "slug", name="uk_brands_tenant_slug"),
        Index("ix_brands_tenant_name", "tenant_id", "name"),
        Index("ix_brands_featured", "is_featured"),
        Index("ix_brands_active", "is_active"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    name: Mapped[str] = mapped_column(String(120), nullable=False, comment="品牌名称")
    slug: Mapped[str] = mapped_column(String(180), nullable=False, comment="SEO 友好 URL")
    english_name: Mapped[str | None] = mapped_column(String(120), nullable=True)
    logo_url: Mapped[str | None] = mapped_column(String(500), nullable=True)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    website_url: Mapped[str | None] = mapped_column(String(500), nullable=True)
    country: Mapped[str | None] = mapped_column(String(80), nullable=True)
    sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    is_featured: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=0)
    is_active: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=1)
    meta_title: Mapped[str | None] = mapped_column(String(160), nullable=True)
    meta_description: Mapped[str | None] = mapped_column(String(320), nullable=True)

    products = relationship("Product", back_populates="brand", lazy="noload")

    def __init__(self, **kwargs):
        kwargs.setdefault("sort_order", 0)
        kwargs.setdefault("is_featured", 0)
        kwargs.setdefault("is_active", 1)
        super().__init__(**kwargs)

    def __repr__(self) -> str:
        return f"<Brand id={self.id} slug={self.slug!r}>"
