from sqlalchemy import BigInteger, String, Boolean, Text
from sqlalchemy.orm import Mapped, mapped_column
from app.core.models.base import Base, TimestampMixin


class StorageProfile(Base, TimestampMixin):
    """存储账号配置 — 可被多个租户复用，也可用作静态资源分发账号"""

    __tablename__ = "storage_profiles"

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    name: Mapped[str] = mapped_column(String(100), nullable=False, comment="展示名称，如 R2-海外默认")
    purpose: Mapped[str] = mapped_column(String(20), nullable=False, default="tenant_data", comment="tenant_data=租户图片 static_assets=前端静态资源")
    provider: Mapped[str] = mapped_column(String(20), nullable=False, comment="local/s3/r2/oss")
    bucket: Mapped[str | None] = mapped_column(String(200), nullable=True, comment="存储桶名称")
    region: Mapped[str | None] = mapped_column(String(50), nullable=True, comment="区域，如 us-east-1")
    endpoint_url: Mapped[str | None] = mapped_column(String(255), nullable=True, comment="自定义 endpoint，R2/OSS/Lightsail 需要")
    access_key: Mapped[str | None] = mapped_column(String(255), nullable=True, comment="访问密钥 ID")
    secret_key: Mapped[str | None] = mapped_column(String(255), nullable=True, comment="访问密钥密码，敏感信息")
    public_url_base: Mapped[str | None] = mapped_column(String(255), nullable=True, comment="公开访问域名，如自定义CDN域名")
    use_acl: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, comment="是否设置对象ACL，Lightsail/R2需关闭")
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, comment="是否启用")
    migration_skip_hosts: Mapped[str | None] = mapped_column(Text, nullable=True, comment="迁移时跳过的域名列表（JSON数组），如 [\"go.cin7.com\"]")

    def to_storage_cfg(self) -> dict:
        """转换成 storage.get_storage(cfg) 期望的 dict 形状"""
        return {
            "cdn_provider": self.provider,
            "cdn_s3_bucket": self.bucket,
            "cdn_s3_region": self.region or "us-east-1",
            "cdn_s3_access_key": self.access_key,
            "cdn_s3_secret_key": self.secret_key,
            "cdn_s3_endpoint_url": self.endpoint_url,
            "cdn_r2_endpoint": self.endpoint_url,
            "cdn_s3_use_acl": self.use_acl,
            "cdn_oss_bucket": self.bucket,
            "cdn_oss_endpoint": self.endpoint_url,
            "cdn_oss_access_key": self.access_key,
            "cdn_oss_secret_key": self.secret_key,
            "cdn_public_url": self.public_url_base,
        }

    def __repr__(self) -> str:
        return f"<StorageProfile id={self.id} name={self.name!r} provider={self.provider}>"
