import logging

from django.contrib.auth import get_user_model
from django.db import models
from django.db.models import UniqueConstraint
from django.utils.translation import gettext_lazy as _

from console_base.managers import LCBaseQuerySet
from console_base.models import BaseUUIDPKModel
from console_webauthn.choices import CredentialFormat, DeviceType

logger = logging.getLogger(__name__)
User = get_user_model()


# ---------------------------------------------------------------------------
class Registration(BaseUUIDPKModel):
    """
    WebAuthn Registration Event
    """

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    challenge = models.TextField(blank=True, null=True)

    objects = LCBaseQuerySet.as_manager()  # type: ignore[django-manager-missing]

    class Meta:
        verbose_name = "registration"
        verbose_name_plural = _("registrations")

    def __str__(self) -> str:
        return self.challenge or 'Challenge NA'


# ---------------------------------------------------------------------------
class Authentication(BaseUUIDPKModel):
    """
    WebAuthn Authentication Event
    """

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    challenge = models.TextField(blank=True, null=True)

    objects = LCBaseQuerySet.as_manager()  # type: ignore[django-manager-missing]

    class Meta:
        verbose_name = "authentication"
        verbose_name_plural = _("authentications")

    def __str__(self) -> str:
        return self.challenge or 'Challenge NA'


# ---------------------------------------------------------------------------
class Credential(BaseUUIDPKModel):
    """
    WebAuthn Registered Credential (YubiKey, Phone, etc)
    """

    css_icon = 'fas fa-sim-card'
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="webauthn")
    user_verified = models.BooleanField(default=False)
    name = models.TextField(verbose_name="Name", blank=True, null=True)
    credential_public_key = models.TextField(blank=True, null=True)
    credential_id = models.TextField(blank=True, null=True)
    aaguid = models.TextField(blank=True, null=True)
    credential_fmt = models.TextField(
        choices=CredentialFormat.choices,
        default=CredentialFormat.Packed,
    )
    device_type = models.TextField(choices=DeviceType.choices, default=DeviceType.MultiDevice)
    current_sign_count = models.PositiveIntegerField(default=0)

    objects = LCBaseQuerySet.as_manager()  # type: ignore[django-manager-missing]

    class Meta:
        verbose_name = "credential"
        verbose_name_plural = _("credentials")

        constraints = (
            UniqueConstraint(
                name='device_unique_credential_id',
                fields=['credential_id'],
            ),
            UniqueConstraint(
                name='name_user_user_unique',
                fields=('name', 'user'),
            ),
        )

    def __str__(self) -> str:
        return self.name or ''
