"""
Admin actions for mock webhook generation.

Provides admin interface for triggering mock webhooks on GitHub installations.
"""

from __future__ import annotations

from django.contrib import messages

from mocking.services import MockWebhookService


def generate_mock_webhooks(modeladmin, request, queryset):
    """Admin action to generate mock webhooks for selected installations.

    Generates 5 random webhooks per selected installation and sends them
    to the configured webhook endpoint.
    """
    service = MockWebhookService()
    total_sent = 0
    total_errors = 0

    for installation in queryset:
        try:
            results = service.generate_webhooks_for_installation(
                installation,
                count=5,
                dry_run=False,
            )
            sent = sum(1 for r in results if r.get("status") == "sent")
            errors = sum(1 for r in results if r.get("status") == "error")
            total_sent += sent
            total_errors += errors
        except Exception as e:
            messages.error(
                request,
                f"Error generating webhooks for {installation.account_login}: {str(e)}",
            )
            total_errors += 1

    if total_sent > 0:
        messages.success(
            request,
            f"Successfully sent {total_sent} mock webhooks.",
        )
    if total_errors > 0:
        messages.warning(
            request,
            f"{total_errors} webhooks failed to send.",
        )


generate_mock_webhooks.short_description = "Generate mock webhooks (5 per installation)"


def generate_mock_webhooks_dry_run(modeladmin, request, queryset):
    """Admin action to preview mock webhooks without sending them.

    Shows what webhooks would be generated for the selected installations.
    """
    service = MockWebhookService()
    total_previewed = 0

    for installation in queryset:
        try:
            results = service.generate_webhooks_for_installation(
                installation,
                count=5,
                dry_run=True,
            )
            total_previewed += len(results)

            for result in results:
                event = result.get("event_type", "unknown")
                repo = result.get("repository", "unknown")
                action = result.get("payload_preview", {}).get("action", "unknown")
                messages.info(
                    request,
                    f"Would send: {event}:{action} to {repo}",
                )
        except Exception as e:
            messages.error(
                request,
                f"Error previewing webhooks for {installation.account_login}: {str(e)}",
            )

    messages.success(
        request,
        f"Preview complete. Would generate {total_previewed} webhooks.",
    )


generate_mock_webhooks_dry_run.short_description = "Preview mock webhooks (dry run)"


# Register admin actions with GitHubInstallation model
# This is done via the integrations app's admin.py to avoid circular imports
# Add these actions to the GitHubInstallationAdmin class:
#
#   from mocking.admin import generate_mock_webhooks, generate_mock_webhooks_dry_run
#
#   @admin.register(GitHubInstallation)
#   class GitHubInstallationAdmin(admin.ModelAdmin):
#       actions = [generate_mock_webhooks, generate_mock_webhooks_dry_run]
