"""
Django admin configuration for the Core application.

This module provides admin interfaces for core models including
slug history for SEO redirect management.

Performance targets:
- List views: < 8 queries
- Page load time: < 500ms for 100 records
"""

from django.contrib import admin
from django.utils.html import format_html

from apps.core.admin.base import BaseModelAdmin
from apps.core.admin.mixins import (
    ExportActionMixin,
    QueryOptimizationMixin,
    ReadOnlyAdminMixin,
)

from .models import SlugHistory


@admin.register(SlugHistory)
class SlugHistoryAdmin(ReadOnlyAdminMixin, QueryOptimizationMixin, ExportActionMixin, BaseModelAdmin):
    """
    Admin interface for SlugHistory management.

    Read-only admin for viewing slug history records used for
    SEO redirects. Records are automatically created when slugs
    change and should not be manually modified.

    Query optimizations:
    - select_related: content_type
    - prefetch_related: content_object (where applicable)
    """

    list_display = (
        "content_object_link",
        "old_slug",
        "content_type_display",
        "created_at",
    )
    list_filter = ("content_type", "created_at")
    list_select_related = ["content_type"]
    search_fields = ("old_slug", "object_id")
    readonly_fields = ("content_type", "object_id", "old_slug", "created_at")
    date_hierarchy = "created_at"
    ordering = ("-created_at",)

    export_fields = ["id", "content_type", "object_id", "old_slug", "created_at"]
    export_filename_prefix = "slug_history"

    fieldsets = (
        (
            "Slug Information",
            {
                "fields": ("old_slug",),
                "description": "The previous slug value that should redirect to the current URL.",
            },
        ),
        (
            "Related Object",
            {
                "fields": ("content_type", "object_id"),
                "description": "The object this slug history belongs to.",
            },
        ),
        (
            "Metadata",
            {
                "fields": ("created_at",),
                "classes": ("collapse",),
                "description": "When this slug history record was created.",
            },
        ),
    )

    @admin.display(description="Object")
    def content_object_link(self, obj):
        """Create a link to the related object's admin page."""
        try:
            content_obj = obj.content_object
            if content_obj:
                # Try to get admin URL
                from django.urls import reverse

                app_label = obj.content_type.app_label
                model_name = obj.content_type.model
                try:
                    url = reverse(
                        f"admin:{app_label}_{model_name}_change",
                        args=[content_obj.pk],
                    )
                    return format_html(
                        '<a href="{}">{}</a>',
                        url,
                        str(content_obj)[:50],
                    )
                except Exception:
                    # Fall back to object's absolute URL if available
                    if hasattr(content_obj, "get_absolute_url"):
                        return format_html(
                            '<a href="{}">{}</a>',
                            content_obj.get_absolute_url(),
                            str(content_obj)[:50],
                        )
            return str(content_obj)[:50] if content_obj else "-"
        except Exception:
            return format_html('<span style="color: red;">Object not found</span>')

    @admin.display(description="Type")
    def content_type_display(self, obj):
        """Display content type in a readable format."""
        if obj.content_type:
            return f"{obj.content_type.app_label}.{obj.content_type.model}"
        return "-"

    @admin.action(description="Export for SEO redirects")
    def export_for_seo(self, request, queryset):
        """Export slug history as SEO redirect rules."""
        return self.export_to_csv(request, queryset)

    @admin.action(description="Cleanup old history (>1 year)")
    def cleanup_old_history(self, request, queryset):
        """Delete slug history older than 1 year."""
        from datetime import timedelta

        from django.utils import timezone

        cutoff = timezone.now() - timedelta(days=365)
        old_records = queryset.filter(created_at__lt=cutoff)
        count = old_records.count()
        old_records.delete()
        self.message_user(request, f"Deleted {count} old slug history records.")

    def get_actions(self, request):
        """Add custom actions to the admin."""
        actions = super().get_actions(request)
        actions["export_for_seo"] = (
            self.export_for_seo,
            "export_for_seo",
            "Export for SEO redirects",
        )
        if request.user.is_superuser:
            actions["cleanup_old_history"] = (
                self.cleanup_old_history,
                "cleanup_old_history",
                "Cleanup old history (>1 year)",
            )
        return actions
