"""
Public API Admin Configuration

Admin interface for managing API tokens and webhook subscriptions.
"""

from django.contrib import admin
from .models import APIToken, WebhookSubscription, WebhookDelivery


@admin.register(APIToken)
class APITokenAdmin(admin.ModelAdmin):
    """Admin interface for API tokens."""

    list_display = [
        'name',
        'key_prefix',
        'tenant',
        'is_active',
        'scopes_display',
        'created_at',
        'last_used_at',
        'expires_at',
    ]
    list_filter = ['is_active', 'tenant', 'created_at']
    search_fields = ['name', 'key_prefix', 'tenant__name']
    readonly_fields = ['key_hash', 'key_prefix', 'created_at', 'last_used_at', 'created_by']
    ordering = ['-created_at']

    fieldsets = (
        (None, {
            'fields': ('name', 'tenant', 'is_active')
        }),
        ('Authentication', {
            'fields': ('key_prefix', 'key_hash'),
            'description': 'The full key is only shown once when created.'
        }),
        ('Permissions', {
            'fields': ('scopes',)
        }),
        ('Expiration', {
            'fields': ('expires_at',)
        }),
        ('Rate Limiting', {
            'fields': ('rate_limit_override',),
            'description': 'Override the default rate limit (requests/hour). Leave blank for default.'
        }),
        ('Metadata', {
            'fields': ('created_by', 'created_at', 'last_used_at'),
            'classes': ('collapse',)
        }),
    )

    def scopes_display(self, obj):
        """Display scopes as a comma-separated list."""
        return ', '.join(obj.scopes[:3]) + ('...' if len(obj.scopes) > 3 else '')
    scopes_display.short_description = 'Scopes'


@admin.register(WebhookSubscription)
class WebhookSubscriptionAdmin(admin.ModelAdmin):
    """Admin interface for webhook subscriptions."""

    list_display = [
        'url_display',
        'tenant',
        'api_token',
        'events_display',
        'is_active',
        'failure_count',
        'last_triggered_at',
    ]
    list_filter = ['is_active', 'tenant', 'created_at']
    search_fields = ['url', 'tenant__name', 'api_token__name']
    readonly_fields = ['secret', 'created_at', 'last_triggered_at', 'last_success_at', 'last_failure_at']
    ordering = ['-created_at']

    fieldsets = (
        (None, {
            'fields': ('tenant', 'api_token', 'url', 'is_active')
        }),
        ('Events', {
            'fields': ('events',)
        }),
        ('Security', {
            'fields': ('secret',),
            'description': 'Secret for HMAC-SHA256 signature verification'
        }),
        ('Health', {
            'fields': ('failure_count', 'last_triggered_at', 'last_success_at', 'last_failure_at'),
            'classes': ('collapse',)
        }),
        ('Metadata', {
            'fields': ('description', 'created_at'),
            'classes': ('collapse',)
        }),
    )

    def url_display(self, obj):
        """Display truncated URL."""
        return obj.url[:50] + ('...' if len(obj.url) > 50 else '')
    url_display.short_description = 'URL'

    def events_display(self, obj):
        """Display event count."""
        return f'{len(obj.events)} events'
    events_display.short_description = 'Events'


@admin.register(WebhookDelivery)
class WebhookDeliveryAdmin(admin.ModelAdmin):
    """Admin interface for webhook deliveries."""

    list_display = [
        'event_type',
        'subscription_url',
        'success',
        'response_status',
        'retry_count',
        'created_at',
        'delivered_at',
    ]
    list_filter = ['success', 'event_type', 'created_at']
    search_fields = ['event_id', 'subscription__url']
    readonly_fields = [
        'id', 'subscription', 'event_type', 'event_id', 'payload',
        'response_status', 'response_body', 'delivered_at', 'created_at',
        'success', 'retry_count', 'next_retry_at', 'error_message'
    ]
    ordering = ['-created_at']

    def subscription_url(self, obj):
        """Display subscription URL."""
        return obj.subscription.url[:40] + '...' if len(obj.subscription.url) > 40 else obj.subscription.url
    subscription_url.short_description = 'Subscription'

    def has_add_permission(self, request):
        """Disable adding deliveries manually."""
        return False

    def has_change_permission(self, request, obj=None):
        """Disable editing deliveries."""
        return False
