from sqlalchemy import BigInteger, String, UniqueConstraint, Index, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column
from app.core.models.base import Base, TimestampMixin


class CustomerOAuthAccount(Base, TimestampMixin):
    """客户第三方登录账号 — openid/unionid 与 customer 的映射"""

    __tablename__ = "customer_oauth_accounts"
    __table_args__ = (
        UniqueConstraint("tenant_id", "provider", "appid", "openid", name="uk_oauth"),
        Index("ix_oauth_customer", "tenant_id", "customer_id"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    tenant_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("tenants.id", ondelete="RESTRICT"), nullable=False
    )
    customer_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("customers.id", ondelete="CASCADE"), nullable=False
    )
    provider: Mapped[str] = mapped_column(
        String(50), nullable=False,
        comment="wechat_miniapp | wechat_mp | google"
    )
    appid: Mapped[str] = mapped_column(String(64), nullable=False)
    openid: Mapped[str] = mapped_column(String(128), nullable=False)
    unionid: Mapped[str | None] = mapped_column(String(128), nullable=True)

    def __repr__(self) -> str:
        return f"<CustomerOAuthAccount provider={self.provider!r} openid={self.openid!r}>"
