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


class Command(BaseCommand):
    help = 'Fix duplicate Google OAuth entries'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('=== Fixing Google OAuth Duplicates ===\n'))
        
        # Get all Google social apps
        google_apps = SocialApp.objects.filter(provider='google')
        count = google_apps.count()
        
        self.stdout.write(f'Found {count} Google OAuth app(s)')
        
        if count > 1:
            # Delete all Google apps
            google_apps.delete()
            self.stdout.write(self.style.SUCCESS('✓ Deleted all duplicate Google OAuth apps'))
            self.stdout.write(self.style.WARNING('\nYou need to setup Google OAuth again:'))
            self.stdout.write('Run: python manage.py setup_google_oauth')
        elif count == 1:
            self.stdout.write(self.style.SUCCESS('✓ Only one Google OAuth app found (correct)'))
            app = google_apps.first()
            self.stdout.write(f'   Provider: {app.provider}')
            self.stdout.write(f'   Name: {app.name}')
            self.stdout.write(f'   Client ID: {app.client_id[:20]}...')
        else:
            self.stdout.write(self.style.WARNING('✗ No Google OAuth app found'))
            self.stdout.write('Run: python manage.py setup_google_oauth')
        
        self.stdout.write('\n=== Done ===\n')

