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

from core.choices import ServiceType
from core.models import TimeStampedModel


class HostingAccount(TimeStampedModel):
    class PanelType(models.TextChoices):
        CPANEL = "cpanel", "cPanel"
        PLESK = "plesk", "Plesk"
        DIRECTADMIN = "directadmin", "DirectAdmin"
        CUSTOM = "custom", "Personalizado"
        NONE = "none", "Sem painel"

    class Status(models.TextChoices):
        PROVISIONING = "provisioning", "Em ativação"
        ACTIVE = "active", "Ativo"
        LIMITED = "limited", "Limitado / quota elevada"
        MIGRATING = "migrating", "Em migração"
        MAINTENANCE = "maintenance", "Em manutenção"
        SUSPENDED = "suspended", "Suspenso"
        OFFLINE = "offline", "Indisponível"
        CANCELLED = "cancelled", "Cancelado"
        UNKNOWN = "unknown", "Por confirmar"

    service = models.OneToOneField(
        "services.Service", on_delete=models.CASCADE, related_name="hosting_details", verbose_name="Serviço"
    )
    primary_domain = models.ForeignKey(
        "domains.Domain", on_delete=models.SET_NULL, null=True, blank=True, related_name="hosting_accounts", verbose_name="Domínio principal"
    )
    server = models.ForeignKey(
        "technical.Server", on_delete=models.SET_NULL, null=True, blank=True, related_name="hosting_accounts", verbose_name="Servidor"
    )
    plan_name = models.CharField("Plano", max_length=120, blank=True)
    panel_type = models.CharField("Painel", max_length=20, choices=PanelType.choices, default=PanelType.CPANEL)
    account_reference = models.CharField(
        "Referência da conta", max_length=150, blank=True, help_text="Identificador ou referência no cofre; nunca guardar a password."
    )
    document_root = models.CharField("Pasta principal", max_length=500, blank=True)
    disk_quota_mb = models.PositiveBigIntegerField("Espaço contratado (MB)", null=True, blank=True)
    disk_used_mb = models.PositiveBigIntegerField("Espaço usado (MB)", null=True, blank=True)
    monthly_traffic_mb = models.PositiveBigIntegerField("Tráfego mensal (MB)", null=True, blank=True)
    email_account_limit = models.PositiveIntegerField("Limite de emails", null=True, blank=True)
    php_version = models.CharField("Versão PHP", max_length=30, blank=True)
    status = models.CharField("Estado do alojamento", max_length=20, choices=Status.choices, default=Status.ACTIVE)
    notes = models.TextField("Notas", blank=True)

    class Meta:
        verbose_name = "Alojamento"
        verbose_name_plural = "Alojamentos"
        ordering = ["service__client__name", "service__name"]

    def clean(self):
        if self.service_id and self.service.service_type != ServiceType.HOSTING:
            raise ValidationError({"service": "A ficha de alojamento tem de estar ligada a um serviço do tipo Alojamento web."})

    def __str__(self):
        return self.service.name
