from allauth.socialaccount.models import SocialApp
from django.core.management.base import BaseCommand
from django.test import Client


class Command(BaseCommand):
    help = "Test Discord OAuth2 authentication flow"

    def handle(self, *args, **options):
        client = Client(HTTP_HOST="localhost:8000")

        # Get Discord app
        try:
            discord_app = SocialApp.objects.get(provider="discord")
            self.stdout.write("Found Discord app configuration:")
            self.stdout.write(f"Client ID: {discord_app.client_id}")

            # Test login URL
            login_url = "/accounts/discord/login/"
            response = client.get(login_url, HTTP_HOST="localhost:8000")
            self.stdout.write(f"\nTesting login URL: {login_url}")
            self.stdout.write(f"Status code: {response.status_code}")

            if response.status_code == 302:
                redirect_url = response["Location"]
                self.stdout.write(f"Redirects to: {redirect_url}")

                # Parse OAuth2 parameters
                self.stdout.write("\nOAuth2 Parameters:")
                if "client_id=" in redirect_url:
                    self.stdout.write("✓ client_id parameter present")
                if "redirect_uri=" in redirect_url:
                    self.stdout.write("✓ redirect_uri parameter present")
                if "scope=" in redirect_url:
                    self.stdout.write("✓ scope parameter present")
                if "response_type=" in redirect_url:
                    self.stdout.write("✓ response_type parameter present")
                if "code_challenge=" in redirect_url:
                    self.stdout.write("✓ PKCE enabled (code_challenge present)")

            # Show callback URL
            callback_url = "http://localhost:8000/accounts/discord/login/callback/"
            self.stdout.write("\nCallback URL to configure in Discord Developer Portal:")
            self.stdout.write(callback_url)

            # Show frontend login URL
            frontend_url = "http://localhost:5173"
            self.stdout.write("\nFrontend configuration:")
            self.stdout.write(f"Frontend URL: {frontend_url}")
            self.stdout.write("Discord login button should use:")
            self.stdout.write("/accounts/discord/login/?process=login")

            # Show allauth URLs
            self.stdout.write("\nAllauth URLs:")
            self.stdout.write("Login URL: /accounts/discord/login/?process=login")
            self.stdout.write("Callback URL: /accounts/discord/login/callback/")

        except SocialApp.DoesNotExist:
            self.stdout.write(self.style.ERROR("Discord app not found"))
