"""
Management command to create a Stripe webhook endpoint for local development.

Usage:
    docker compose -f docker-compose.local.yml exec django python manage.py setup_stripe_webhook --url https://dd59f59c217b.ngrok-free.app/stripe/webhook/

This will:
1. Create a webhook endpoint in Stripe with the specified URL
2. Sync it to the local djstripe database
3. Store the webhook secret in PlatformSettings
"""

from django.core.management.base import BaseCommand

import stripe
from djstripe.models import WebhookEndpoint

from smoothschedule.platform.admin.models import PlatformSettings


class Command(BaseCommand):
    help = "Create a Stripe webhook endpoint for local development"

    DEFAULT_EVENTS = [
        "checkout.session.completed",
        "checkout.session.expired",
        "customer.created",
        "customer.updated",
        "customer.deleted",
        "customer.subscription.created",
        "customer.subscription.updated",
        "customer.subscription.deleted",
        "customer.subscription.trial_will_end",
        "invoice.created",
        "invoice.finalized",
        "invoice.paid",
        "invoice.payment_failed",
        "invoice.payment_action_required",
        "payment_intent.succeeded",
        "payment_intent.payment_failed",
        "payment_intent.canceled",
        "payment_method.attached",
        "payment_method.detached",
        "account.updated",
        "account.application.authorized",
        "account.application.deauthorized",
    ]

    def add_arguments(self, parser):
        parser.add_argument(
            "--url",
            type=str,
            required=True,
            help="The webhook endpoint URL (must be HTTPS)",
        )
        parser.add_argument(
            "--description",
            type=str,
            default="SmoothSchedule Local Development Webhook",
            help="Description for the webhook endpoint",
        )
        parser.add_argument(
            "--set-primary",
            action="store_true",
            help="Set this webhook as the primary webhook in PlatformSettings",
        )

    def handle(self, *args, **options):
        url = options["url"]
        description = options["description"]
        set_primary = options["set_primary"]

        # Validate URL
        if not url.startswith("https://"):
            self.stderr.write(
                self.style.ERROR("Webhook URL must use HTTPS")
            )
            return

        # Get platform settings
        settings = PlatformSettings.get_instance()
        if not settings.has_stripe_keys():
            self.stderr.write(
                self.style.ERROR("Stripe keys not configured in PlatformSettings")
            )
            return

        try:
            stripe.api_key = settings.get_stripe_secret_key()

            # Check if webhook already exists for this URL
            existing_webhooks = stripe.WebhookEndpoint.list(limit=100)
            for wh in existing_webhooks.data:
                if wh.url == url:
                    self.stdout.write(
                        self.style.WARNING(f"Webhook already exists for URL: {url}")
                    )
                    self.stdout.write(f"  ID: {wh.id}")
                    self.stdout.write(f"  Status: {wh.status}")

                    # Sync to local database
                    local_wh = WebhookEndpoint.sync_from_stripe_data(wh)

                    if set_primary and local_wh.secret:
                        settings.stripe_webhook_secret = local_wh.secret
                        settings.save()
                        self.stdout.write(
                            self.style.SUCCESS("Set as primary webhook in PlatformSettings")
                        )

                    return

            # Create new webhook
            self.stdout.write(f"Creating webhook endpoint for: {url}")

            endpoint = stripe.WebhookEndpoint.create(
                url=url,
                enabled_events=self.DEFAULT_EVENTS,
                description=description,
                metadata={"created_by": "smoothschedule_setup_command"},
            )

            # The secret is only returned on creation
            webhook_secret = endpoint.secret

            self.stdout.write(self.style.SUCCESS("Webhook created successfully in Stripe!"))
            self.stdout.write(f"  ID: {endpoint.id}")
            self.stdout.write(f"  URL: {endpoint.url}")
            self.stdout.write(f"  Status: {endpoint.status}")
            self.stdout.write(f"  Secret: {webhook_secret}")

            # Try to sync to local database (may fail in multi-tenant setup)
            try:
                local_wh = WebhookEndpoint.sync_from_stripe_data(endpoint)
                local_wh.secret = webhook_secret
                local_wh.save()
                self.stdout.write(self.style.SUCCESS("Synced to local djstripe database"))
            except Exception as sync_error:
                self.stdout.write(
                    self.style.WARNING(f"Could not sync to djstripe database: {sync_error}")
                )
                self.stdout.write("  (This is okay for local development)")

            if set_primary:
                settings.stripe_webhook_secret = webhook_secret
                settings.save()
                self.stdout.write(
                    self.style.SUCCESS("Set as primary webhook in PlatformSettings")
                )

            self.stdout.write("")
            self.stdout.write("Events subscribed to:")
            for event in self.DEFAULT_EVENTS:
                self.stdout.write(f"  - {event}")

        except stripe.error.AuthenticationError:
            self.stderr.write(
                self.style.ERROR("Invalid Stripe API key")
            )
        except Exception as e:
            self.stderr.write(
                self.style.ERROR(f"Error creating webhook: {e}")
            )
