from django.contrib import admin
from .models import ContactFormSubmission


@admin.register(ContactFormSubmission)
class ContactFormSubmissionAdmin(admin.ModelAdmin):
    list_display = ("created_at", "processing_status", "spam_category", "category", "name", "email", "ip_address")
    list_filter = ("processing_status", "spam_category", "category", "created_at")
    search_fields = ("name", "email", "contact", "message", "source_page", "ip_address")
    actions = ("requeue_submissions",)
    readonly_fields = (
        "name",
        "email",
        "contact",
        "category",
        "message",
        "source_page",
        "ip_address",
        "user_agent",
        "processing_status",
        "spam_category",
        "spam_source",
        "spam_checked_at",
        "scan_attempt_count",
        "send_attempt_count",
        "next_attempt_at",
        "processing_started_at",
        "notification_sent_at",
        "user_copy_sent_at",
        "last_error",
        "created_at",
        "updated_at",
    )

    @admin.action(description="Requeue selected contact submissions")
    def requeue_submissions(self, request, queryset):
        eligible = queryset.filter(
            processing_status__in=[
                ContactFormSubmission.STATUS_BLOCKED,
                ContactFormSubmission.STATUS_FAILED,
                ContactFormSubmission.STATUS_RATE_LIMITED,
            ]
        )
        updated = eligible.update(
            processing_status=ContactFormSubmission.STATUS_QUEUED,
            spam_category=None,
            spam_source="",
            spam_checked_at=None,
            scan_attempt_count=0,
            send_attempt_count=0,
            next_attempt_at=None,
            processing_started_at=None,
            last_error="",
        )
        self.message_user(request, f"Requeued {updated} contact submission(s).")
