from django.core.exceptions import ValidationError
from django.db import models

from core.choices import ServiceType
from core.models import Provider, TimeStampedModel
from .validators import validate_domain_name


class Domain(TimeStampedModel):
    class DomainStatus(models.TextChoices):
        PENDING = "pending", "A aguardar registo / validação"
        ACTIVE = "active", "Ativo"
        EXPIRING = "expiring", "A expirar"
        GRACE = "grace", "Período de tolerância"
        EXPIRED = "expired", "Expirado"
        TRANSFER_IN = "transfer_in", "Transferência de entrada"
        TRANSFERRED = "transferred", "Transferido para outro fornecedor"
        SUSPENDED = "suspended", "Suspenso"
        CANCELLED = "cancelled", "Cancelado"
        COMPLIMENTARY = "complimentary", "Oferta"
        CLIENT_DIRECT = "client_direct", "Pago diretamente pelo cliente"

    class DNSManagement(models.TextChoices):
        INTERNAL = "internal", "Gerido internamente"
        REGISTRAR = "registrar", "Gerido no registador"
        CLIENT = "client", "Gerido pelo cliente"
        EXTERNAL = "external", "Fornecedor externo"
        UNKNOWN = "unknown", "Por confirmar"

    service = models.OneToOneField(
        "services.Service", on_delete=models.CASCADE, related_name="domain_details", verbose_name="Serviço"
    )
    domain_name = models.CharField("Domínio", max_length=253, unique=True, validators=[validate_domain_name], db_index=True)
    registrar = models.ForeignKey(
        Provider, on_delete=models.SET_NULL, null=True, blank=True, related_name="domains", verbose_name="Registador"
    )
    registered_on = models.DateField("Data de criação", null=True, blank=True)
    status = models.CharField("Estado do domínio", max_length=20, choices=DomainStatus.choices, default=DomainStatus.ACTIVE, db_index=True)
    auto_renew_at_registrar = models.BooleanField("Auto-renovação no registador", default=False)
    dns_management = models.CharField("Gestão DNS", max_length=20, choices=DNSManagement.choices, default=DNSManagement.UNKNOWN)
    nameservers = models.TextField("Nameservers", blank=True, help_text="Um nameserver por linha.")
    transfer_lock = models.BooleanField("Bloqueio de transferência", default=True)
    auth_code_reference = models.CharField(
        "Referência do AuthCode", max_length=150, blank=True, help_text="Não guardar o código; indicar apenas onde está guardado."
    )
    notes = models.TextField("Notas", blank=True)

    class Meta:
        verbose_name = "Domínio"
        verbose_name_plural = "Domínios"
        ordering = ["domain_name"]

    def clean(self):
        if self.service_id and self.service.service_type != ServiceType.DOMAIN:
            raise ValidationError({"service": "A ficha de domínio tem de estar ligada a um serviço do tipo Domínio."})

    def save(self, *args, **kwargs):
        self.domain_name = self.domain_name.strip().lower().rstrip(".")
        super().save(*args, **kwargs)

    @property
    def expires_on(self):
        return self.service.next_renewal_date

    def __str__(self):
        return self.domain_name
