from django.conf import settings
from django.db import models
from django.utils import timezone

from core.models import TimeStampedModel


class InternalTask(TimeStampedModel):
    class TaskType(models.TextChoices):
        RENEW_SERVICE = "renew_service", "Renovar serviço"
        CONFIRM_PAYMENT = "confirm_payment", "Confirmar pagamento"
        CONTACT_CLIENT = "contact_client", "Contactar cliente"
        UPDATE_DNS = "update_dns", "Atualizar DNS"
        VERIFY_SSL = "verify_ssl", "Verificar SSL"
        CREATE_BACKUP = "create_backup", "Criar backup"
        TECHNICAL_CHECK = "technical_check", "Verificação técnica"
        OTHER = "other", "Outro"

    class Priority(models.TextChoices):
        LOW = "low", "Baixa"
        NORMAL = "normal", "Normal"
        HIGH = "high", "Alta"
        URGENT = "urgent", "Urgente"

    class Status(models.TextChoices):
        TODO = "todo", "Por fazer"
        IN_PROGRESS = "in_progress", "Em curso"
        WAITING = "waiting", "A aguardar"
        BLOCKED = "blocked", "Bloqueada"
        DONE = "done", "Concluída"
        CANCELLED = "cancelled", "Cancelada"

    title = models.CharField("Título", max_length=180)
    task_type = models.CharField("Tipo", max_length=30, choices=TaskType.choices, default=TaskType.OTHER)
    client = models.ForeignKey(
        "clients.Client", on_delete=models.SET_NULL, null=True, blank=True, related_name="internal_tasks", verbose_name="Cliente"
    )
    service = models.ForeignKey(
        "services.Service", on_delete=models.SET_NULL, null=True, blank=True, related_name="internal_tasks", verbose_name="Serviço"
    )
    renewal = models.ForeignKey(
        "billing.Renewal", on_delete=models.SET_NULL, null=True, blank=True, related_name="internal_tasks", verbose_name="Renovação"
    )
    assigned_to = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="assigned_internal_tasks",
        verbose_name="Responsável",
    )
    priority = models.CharField("Prioridade", max_length=15, choices=Priority.choices, default=Priority.NORMAL, db_index=True)
    status = models.CharField("Estado", max_length=20, choices=Status.choices, default=Status.TODO, db_index=True)
    due_date = models.DateField("Data limite", null=True, blank=True, db_index=True)
    completed_at = models.DateTimeField("Concluída em", null=True, blank=True)
    description = models.TextField("Descrição", blank=True)

    class Meta:
        verbose_name = "Tarefa interna"
        verbose_name_plural = "Tarefas internas"
        ordering = ["status", "due_date", "-priority", "title"]
        indexes = [models.Index(fields=["status", "due_date"]), models.Index(fields=["assigned_to", "status"])]

    @property
    def is_overdue(self):
        return bool(self.due_date and self.status not in {self.Status.DONE, self.Status.CANCELLED} and self.due_date < timezone.localdate())

    def save(self, *args, **kwargs):
        if self.status == self.Status.DONE and not self.completed_at:
            self.completed_at = timezone.now()
        elif self.status != self.Status.DONE:
            self.completed_at = None
        super().save(*args, **kwargs)

    def __str__(self):
        return self.title
