"""租户渠道配置模型 — 每个小程序/公众号 AppID 一条记录"""
from sqlalchemy import BigInteger, String, JSON, UniqueConstraint, Index
from sqlalchemy.orm import Mapped, mapped_column

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


class TenantChannel(Base, TenantMixin, TimestampMixin):
    """租户渠道配置 — 每个小程序/公众号 AppID 一条记录"""

    __tablename__ = "tenant_channels"
    __table_args__ = (
        UniqueConstraint("channel", "appid", name="uk_channel_appid"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    channel: Mapped[str] = mapped_column(
        String(50),
        nullable=False,
        server_default="wechat_miniapp",
        comment="渠道标识：wechat_miniapp | wechat_mp | alipay_miniapp",
    )
    appid: Mapped[str] = mapped_column(String(64), nullable=False, comment="微信 AppID")
    app_name: Mapped[str | None] = mapped_column(
        String(100), nullable=True, comment="应用名称"
    )
    status: Mapped[str] = mapped_column(
        String(20),
        nullable=False,
        server_default="active",
        comment="状态：active | suspended | deleted",
    )
    config_json: Mapped[dict | None] = mapped_column(
        JSON,
        nullable=True,
        comment='{"public": {...}, "secret": {"appsecret": ..., "mch_id": ...}}',
    )

    def get_public_config(self) -> dict:
        """获取公开配置"""
        cfg = self.config_json or {}
        return cfg.get("public", {})

    def get_secret(self, key: str) -> str | None:
        """获取密钥配置"""
        cfg = self.config_json or {}
        return cfg.get("secret", {}).get(key)

    def __repr__(self) -> str:
        return f"<TenantChannel channel={self.channel!r} appid={self.appid!r} status={self.status!r}>"
