import uuid

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


class DatabaseCleanupOperation(models.Model):
    class Mode(models.TextChoices):
        SELECTIVE = "selective", "Eliminação seletiva"
        FULL = "full", "Limpeza total do portal"

    class Status(models.TextChoices):
        PREVIEWED = "previewed", "Pré-visualizada"
        RUNNING = "running", "Em execução"
        COMPLETED = "completed", "Concluída"
        FAILED = "failed", "Falhou"
        CANCELLED = "cancelled", "Cancelada"

    code = models.UUIDField("Código", default=uuid.uuid4, editable=False, unique=True)
    mode = models.CharField("Modo", max_length=20, choices=Mode.choices)
    status = models.CharField("Estado", max_length=20, choices=Status.choices, default=Status.PREVIEWED, db_index=True)
    requested_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="database_cleanup_operations",
        verbose_name="Solicitado por",
    )
    selected_groups = models.JSONField("Grupos selecionados", default=list, blank=True)
    effective_groups = models.JSONField("Grupos efetivos", default=list, blank=True)
    options = models.JSONField("Opções", default=dict, blank=True)
    preview = models.JSONField("Pré-visualização", default=dict, blank=True)
    result = models.JSONField("Resultado", default=dict, blank=True)
    backup_path = models.CharField("Cópia de segurança", max_length=500, blank=True)
    error_message = models.TextField("Erro", blank=True)
    created_at = models.DateTimeField("Criado em", auto_now_add=True, db_index=True)
    started_at = models.DateTimeField("Iniciado em", null=True, blank=True)
    completed_at = models.DateTimeField("Concluído em", null=True, blank=True)

    class Meta:
        verbose_name = "Operação de limpeza"
        verbose_name_plural = "Operações de limpeza"
        ordering = ["-created_at"]

    def __str__(self):
        return f"{self.get_mode_display()} — {str(self.code)[:8]}"
