from django.core.management.base import BaseCommand
from allauth.socialaccount.models import SocialApp
from django.contrib.sites.models import Site


class Command(BaseCommand):
    help = 'Setup Google OAuth SocialApp'

    def handle(self, *args, **options):
        # Get or create the site
        site, created = Site.objects.get_or_create(
            id=1,
            defaults={'domain': 'localhost:8000', 'name': 'localhost'}
        )
        
        if created:
            self.stdout.write(
                self.style.SUCCESS(f'Created site: {site.domain}')
            )
        else:
            self.stdout.write(
                self.style.SUCCESS(f'Using existing site: {site.domain}')
            )

        # Check if Google app already exists
        try:
            google_app = SocialApp.objects.get(provider='google')
            self.stdout.write(
                self.style.WARNING('Google SocialApp already exists')
            )
        except SocialApp.DoesNotExist:
            # Create Google SocialApp
            google_app = SocialApp.objects.create(
                provider='google',
                name='Google',
                client_id='586692327134-d58ajv82ls0sibpvie96ss17924t2n4s.apps.googleusercontent.com',
                secret='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'
            )
            self.stdout.write(
                self.style.SUCCESS('Created Google SocialApp')
            )

        # Add site to the app
        google_app.sites.add(site)
        google_app.save()
        
        self.stdout.write(
            self.style.SUCCESS(f'Google SocialApp configured successfully!')
        )
        self.stdout.write(f'App ID: {google_app.id}')
        self.stdout.write(f'Provider: {google_app.provider}')
        self.stdout.write(f'Sites: {list(google_app.sites.all())}')
