from django.contrib import admin
from unfold.admin import ModelAdmin
from unfold.decorators import display

from core.admin_ui import PortalAdminMixin

from .models import DatabaseCleanupOperation


@admin.register(DatabaseCleanupOperation)
class DatabaseCleanupOperationAdmin(PortalAdminMixin, ModelAdmin):
    portal_kicker = "SISTEMA"
    portal_icon = "database"
    portal_tone = "danger"
    list_display = ("created_at", "mode", "status_badge", "requested_by", "completed_at", "backup_path")
    list_filter = ("mode", "status", "created_at")
    search_fields = ("code", "requested_by__username", "requested_by__email", "backup_path", "error_message")
    readonly_fields = (
        "code",
        "mode",
        "status",
        "requested_by",
        "selected_groups",
        "effective_groups",
        "options",
        "preview",
        "result",
        "backup_path",
        "error_message",
        "created_at",
        "started_at",
        "completed_at",
    )
    ordering = ("-created_at",)

    @display(description="Estado", label=True)
    def status_badge(self, obj):
        variants = {
            DatabaseCleanupOperation.Status.PREVIEWED: "warning",
            DatabaseCleanupOperation.Status.RUNNING: "info",
            DatabaseCleanupOperation.Status.COMPLETED: "success",
            DatabaseCleanupOperation.Status.FAILED: "danger",
            DatabaseCleanupOperation.Status.CANCELLED: "neutral",
        }
        return obj.get_status_display(), variants.get(obj.status, "info")

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

    def has_view_permission(self, request, obj=None):
        return bool(request.user and request.user.is_superuser)

    def get_queryset(self, request):
        if not request.user.is_superuser:
            return super().get_queryset(request).none()
        return super().get_queryset(request)
