from sqlalchemy import BigInteger, String, SmallInteger, UniqueConstraint, Index, ForeignKey
from sqlalchemy.dialects.mysql import TINYINT
from sqlalchemy.orm import Mapped, mapped_column
from app.core.models.base import Base, TimestampMixin, TenantMixin


class SeoRedirect(Base, TenantMixin, TimestampMixin):
    """SEO 重定向管理（slug 变更时自动写入 301 记录）"""

    __tablename__ = "seo_redirects"
    __table_args__ = (
        UniqueConstraint("tenant_id", "from_path", name="uk_seo_redirect_tenant_from"),
        Index("ix_seo_redirect_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)
    from_path: Mapped[str] = mapped_column(String(500), nullable=False, comment="旧路径，如 /old-product")
    to_path: Mapped[str] = mapped_column(String(500), nullable=False, comment="新路径，如 /products/new-slug")
    status_code: Mapped[int] = mapped_column(SmallInteger, nullable=False, default=301, comment="301 永久 / 302 临时")
    is_active: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=1)

    def __repr__(self) -> str:
        return f"<SeoRedirect {self.from_path!r} → {self.to_path!r} [{self.status_code}]>"
