# models.py
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import gettext_lazy as _  # 添加导入

from .common import ConfigCommonModel


class EmailSetting(ConfigCommonModel):
    ENABLE_CHOICES = [
        (True, _('启用')),
        (False, _('禁用')),
    ]

    email_enabled = models.BooleanField(
        verbose_name=_('启用邮箱功能'),
        choices=ENABLE_CHOICES,
        default=False,
    )
    email_host = models.CharField(
        verbose_name=_('SMTP服务器'),
        max_length=200,
        blank=True,
        help_text=_("例如QQ邮箱: smtp.qq.com, 企业邮箱: smtp.exmail.qq.com")
    )
    email_user = models.EmailField(
        verbose_name=_('邮箱账号'),
        max_length=200,
        blank=True,
    )
    email_password = models.CharField(
        verbose_name=_('SMTP密码'),
        max_length=200,
        blank=True,
        help_text=_("SMTP服务专用密码，不是邮箱登录密码")
    )
    email_port = models.PositiveIntegerField(
        verbose_name=_('SMTP端口'),
        default=587,
        help_text=_(
            "常见端口说明：\n"
            "• 465端口：使用SSL加密（推荐）\n"
            "• 587端口：使用TLS加密（标准）\n"
            "• 25端口：不加密或TLS（云服务器可能禁用）\n"
            "QQ邮箱推荐使用465或587端口"
        )
    )
    default_sender = models.CharField(
        verbose_name=_('默认发件人'),
        max_length=100,
        blank=True,
        help_text=_("格式：发件人名称 <邮箱地址>，例如：系统通知 <noreply@example.com>")
    )

    class Meta:
        verbose_name = _('邮箱配置')
        verbose_name_plural = _('邮箱配置')

    def clean(self):
        """验证端口和加密设置的合理性"""
        super().clean()
        
        if self.email_port:
            if self.email_port not in [25, 465, 587]:
                raise ValidationError({
                    'email_port': _('端口号必须是25、465或587中的一个')
                })

    def __str__(self):
        return str(_("邮箱全局配置"))

    def get_email_config(self):
        """获取邮件配置字典"""
        return {
            'host': self.email_host,
            'port': self.email_port,
            'username': self.email_user,
            'password': self.email_password,
            'use_tls': self.email_port == 587,  # 587端口使用TLS
            'use_ssl': self.email_port == 465,  # 465端口使用SSL
        }
