#zzj: OAuth认证相关数据模型定义
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _


class OAuthUser(models.Model):
    """OAuth用户模型"""
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        verbose_name=_('用户'),
        blank=True,
        null=True,
        on_delete=models.CASCADE
    )
    openid = models.CharField(max_length=50, verbose_name=_('开放ID'))
    nickname = models.CharField(max_length=50, verbose_name=_('昵称'))
    token = models.CharField(max_length=150, null=True, blank=True, verbose_name=_('访问令牌'))
    picture = models.CharField(max_length=350, blank=True, null=True, verbose_name=_('头像'))
    type = models.CharField(max_length=50, blank=False, null=False, verbose_name=_('类型'))
    email = models.CharField(max_length=50, null=True, blank=True, verbose_name=_('邮箱'))
    metadata = models.TextField(null=True, blank=True, verbose_name=_('元数据'))
    creation_time = models.DateTimeField(_('创建时间'), default=now)
    last_modify_time = models.DateTimeField(_('最后修改时间'), default=now)

    def __str__(self):
        return f"{self.nickname}({self.type})"

    class Meta:
        verbose_name = _('OAuth用户')
        verbose_name_plural = verbose_name
        ordering = ['-creation_time']


class OAuthConfig(models.Model):
    """OAuth配置模型"""
    TYPE_CHOICES = (
        ('weibo', _('微博')),
        ('google', _('谷歌')),
        ('github', 'GitHub'),
        ('facebook', 'FaceBook'),
        ('qq', 'QQ'),
    )

    type = models.CharField(_('类型'), max_length=10, choices=TYPE_CHOICES, default='weibo')
    appkey = models.CharField(max_length=200, verbose_name='AppKey')
    appsecret = models.CharField(max_length=200, verbose_name='AppSecret')
    callback_url = models.CharField(
        max_length=200,
        verbose_name=_('回调地址'),
        blank=False,
        default=''
    )
    is_enable = models.BooleanField(_('是否启用'), default=True, blank=False, null=False)
    creation_time = models.DateTimeField(_('创建时间'), default=now)
    last_modify_time = models.DateTimeField(_('最后修改时间'), default=now)

    def clean(self):
        """验证配置类型唯一性"""
        if OAuthConfig.objects.filter(type=self.type).exclude(id=self.id).exists():
            raise ValidationError(_(f'{self.type}配置已存在'))

    def __str__(self):
        return self.get_type_display()

    class Meta:
        verbose_name = _('OAuth配置')
        verbose_name_plural = verbose_name
        ordering = ['-creation_time']
        constraints = [
            models.UniqueConstraint(fields=['type'], name='unique_oauth_type')
        ]