from sqlalchemy import BigInteger, Boolean, Integer, String, JSON, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.core.models.base import Base, TimestampMixin


class Tenant(Base, TimestampMixin):
    """租户主表 — 多租户体系根节点"""

    __tablename__ = "tenants"

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    name: Mapped[str] = mapped_column(String(100), nullable=False, comment="商店名称")
    domain: Mapped[str] = mapped_column(String(255), nullable=False, unique=True, comment="自定义域名")
    plan_type: Mapped[str] = mapped_column(String(50), nullable=False, default="basic", comment="套餐类型")
    status: Mapped[str] = mapped_column(String(20), nullable=False, default="active", index=True, comment="账号状态")
    extra_config: Mapped[dict | None] = mapped_column(JSON, nullable=True, comment="租户级配置（货币、时区、语言等）")
    storage_profile_id: Mapped[int | None] = mapped_column(
        BigInteger, ForeignKey("storage_profiles.id", ondelete="SET NULL"), nullable=True,
        comment="该租户使用的存储账号",
    )
    storage_quota_mb: Mapped[int] = mapped_column(
        Integer, nullable=False, default=10240, comment="存储配额(MB)"
    )
    storage_used_mb: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0, comment="已用存储(MB)"
    )
    ai_profile_id: Mapped[int | None] = mapped_column(
        BigInteger, ForeignKey("ai_profiles.id", ondelete="SET NULL"), nullable=True,
        comment="该租户使用的 AI 配置（未分配则用平台默认配置）",
    )
    ai_allow_custom: Mapped[bool] = mapped_column(
        Boolean, nullable=False, default=True, comment="是否允许租户自行配置 AI Key（关闭后强制使用分配的 AiProfile）",
    )
    ai_quota_monthly: Mapped[int | None] = mapped_column(
        Integer, nullable=True, comment="每月可调用 AI 次数，NULL=不限额",
    )
    ai_used_this_month: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0, comment="本月已用 AI 调用次数",
    )
    ai_quota_month: Mapped[str | None] = mapped_column(
        String(7), nullable=True, comment="ai_used_this_month 所属的月份（YYYY-MM），跨月懒重置用",
    )
    ai_quota_5h: Mapped[int | None] = mapped_column(
        Integer, nullable=True, comment="5 小时内可调用 AI 次数，NULL=不限",
    )
    ai_quota_weekly: Mapped[int | None] = mapped_column(
        Integer, nullable=True, comment="每周可调用 AI 次数，NULL=不限",
    )

    # ── 关联 ─────────────────────────────────────────────────────
    users = relationship("User", back_populates="tenant", lazy="noload")
    customers = relationship("Customer", back_populates="tenant", lazy="noload")
    products = relationship("Product", back_populates="tenant", lazy="noload")
    orders = relationship("Order", back_populates="tenant", lazy="noload")
    plugin_configs = relationship("PluginConfig", back_populates="tenant", lazy="noload")
    storage_profile = relationship("StorageProfile", lazy="noload")
    ai_profile = relationship("AiProfile", lazy="noload")

    def get_config(self, key: str, default=None):
        """安全读取 extra_config 中的单个配置项"""
        if not self.extra_config:
            return default
        return self.extra_config.get(key, default)

    def __repr__(self) -> str:
        return f"<Tenant id={self.id} name={self.name!r}>"
