"""
Management command to fix duplicate SocialApp entries.
This resolves the MultipleObjectsReturned error when rendering templates with social auth providers.
"""
from django.core.management.base import BaseCommand
from allauth.socialaccount.models import SocialApp


class Command(BaseCommand):
    help = 'Remove duplicate SocialApp entries, keeping only one per provider'

    def handle(self, *args, **options):
        # Get all social apps grouped by provider
        providers = {}
        for app in SocialApp.objects.all():
            if app.provider not in providers:
                providers[app.provider] = []
            providers[app.provider].append(app)

        duplicates_found = False

        # Remove duplicates
        for provider, apps in providers.items():
            if len(apps) > 1:
                duplicates_found = True
                self.stdout.write(
                    self.style.WARNING(f'\nFound {len(apps)} entries for provider: {provider}')
                )
                
                # Keep the first one, delete the rest
                for app in apps[1:]:
                    self.stdout.write(f'  Deleting: {app.name} (ID: {app.id})')
                    app.delete()
                
                self.stdout.write(
                    self.style.SUCCESS(f'  Kept: {apps[0].name} (ID: {apps[0].id})')
                )

        if not duplicates_found:
            self.stdout.write(
                self.style.SUCCESS('✓ No duplicate SocialApp entries found.')
            )
        else:
            self.stdout.write(
                self.style.SUCCESS('\n✓ Duplicate SocialApp entries have been cleaned up.')
            )

        # Display final state
        self.stdout.write('\n--- Final SocialApp Status ---')
        for app in SocialApp.objects.all():
            self.stdout.write(f'{app.provider}: {app.name} (ID: {app.id})')
