"""SSL 相关数据库模型

- Subdomain: 域名资产下的子域名记录（关联域名资产 Asset）
- SiteCert:  站点证书监控记录（探测 https 站点证书的到期情况）
"""

from datetime import date, datetime
from typing import Optional

from sqlmodel import Field, SQLModel

from app.core.timeutils import utcnow


class Subdomain(SQLModel, table=True):
    """子域名记录（挂在域名资产下）"""

    __tablename__ = "subdomains"

    id: Optional[int] = Field(default=None, primary_key=True)
    asset_id: int = Field(
        foreign_key="assets.id", index=True, description="所属域名资产 ID"
    )
    host: str = Field(index=True, description="子域名主机名，如 www / api / blog（@ 表示根域名）")
    record_type: Optional[str] = Field(
        default=None, description="DNS 记录类型：A/CNAME/AAAA/MX/TXT"
    )
    record_value: Optional[str] = Field(
        default=None, description="DNS 记录值（IP 或目标域名）"
    )
    is_active: bool = Field(default=True, description="是否启用/解析中")
    note: Optional[str] = Field(default=None, description="备注（用途）")
    created_at: datetime = Field(default_factory=utcnow, description="创建时间")
    updated_at: datetime = Field(
        default_factory=utcnow,
        sa_column_kwargs={"onupdate": utcnow},
        description="更新时间",
    )


class SiteCert(SQLModel, table=True):
    """站点证书监控记录（探测 https 站点证书到期情况）"""

    __tablename__ = "site_certs"

    id: Optional[int] = Field(default=None, primary_key=True)
    hostname: str = Field(index=True, description="探测目标主机名，如 www.example.com")
    port: int = Field(default=443, description="探测端口")
    asset_id: Optional[int] = Field(
        default=None, foreign_key="assets.id", index=True, description="关联资产 ID（可选）"
    )
    issuer: Optional[str] = Field(default=None, description="签发机构 CN")
    subject_cn: Optional[str] = Field(default=None, description="证书主体 CN")
    valid_from: Optional[date] = Field(default=None, description="证书生效日期")
    valid_to: Optional[date] = Field(default=None, description="证书到期日期")
    fingerprint: Optional[str] = Field(default=None, description="证书指纹 SHA-256")
    status: str = Field(
        default="unknown",
        index=True,
        description="状态：valid/expiring/expired/error/unknown",
    )
    error: Optional[str] = Field(default=None, description="探测失败原因")
    last_checked_at: Optional[datetime] = Field(default=None, description="最近探测时间")
    created_at: datetime = Field(default_factory=utcnow, description="创建时间")
    updated_at: datetime = Field(
        default_factory=utcnow,
        sa_column_kwargs={"onupdate": utcnow},
        description="更新时间",
    )
