"""邮件发送日志模型"""
from sqlalchemy import BigInteger, ForeignKey, String, Text, Integer, SmallInteger
from sqlalchemy.orm import Mapped, mapped_column

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


class EmailLog(Base, TimestampMixin):
    """每封邮件发送记录，记录结果和详细错误信息"""

    __tablename__ = "email_logs"
    __table_args__ = {
        "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="CASCADE"),
        nullable=False,
        index=True,
    )

    to_email:   Mapped[str]      = mapped_column(String(255), nullable=False)
    subject:    Mapped[str]      = mapped_column(String(500), nullable=False, default="")
    status:     Mapped[str]      = mapped_column(String(20),  nullable=False, default="sent",
                                                 comment="sent | failed")

    # SMTP 连接信息（记录当时配置，方便排查）
    smtp_host:  Mapped[str | None] = mapped_column(String(255), nullable=True)
    smtp_port:  Mapped[int | None] = mapped_column(Integer,     nullable=True)

    # 错误详情
    error_type: Mapped[str | None] = mapped_column(String(50),  nullable=True,
                                                    comment="auth_failed|connection_failed|timeout|tls_error|recipient_invalid")
    smtp_code:  Mapped[int | None] = mapped_column(SmallInteger, nullable=True,
                                                    comment="SMTP 响应码，如 535")
    detail:     Mapped[str | None] = mapped_column(Text, nullable=True,
                                                    comment="完整错误消息")

    def __repr__(self) -> str:
        return f"<EmailLog id={self.id} to={self.to_email!r} status={self.status!r}>"
