from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.db import transaction
from apps.business.models import Business, BusinessMembership
from apps.authentication.models import UserProfile

User = get_user_model()


class Command(BaseCommand):
    help = 'Give superusers access to all businesses'

    def add_arguments(self, parser):
        parser.add_argument(
            '--create-owner',
            action='store_true',
            help='Create superuser as OWNER of all businesses',
        )
        parser.add_argument(
            '--user-id',
            type=int,
            help='Process only a specific user ID',
        )

    def get_default_permissions(self):
        """Return the default permission structure"""
        return {
            'inventory': ['create', 'read', 'update', 'delete'],
            'sales': ['create', 'read', 'update', 'delete'],
            'customers': ['create', 'read', 'update', 'delete'],
            'transfers': ['create', 'read', 'update', 'delete', 'approve'],
            'warranty': ['create', 'read', 'update', 'delete'],
            'reports': ['read', 'export'],
            'accounting': ['create', 'read', 'update', 'delete'],
            'users': ['create', 'read', 'update', 'delete'],
            'settings': ['read', 'update'],
        }

    def handle(self, *args, **options):
        create_as_owner = options.get('create_owner', False)
        specific_user_id = options.get('user_id')
        role = 'OWNER' if create_as_owner else 'ADMIN'
        
        # Get superuser IDs first to avoid datetime conversion issues
        try:
            if specific_user_id:
                superuser_ids = list(
                    User.objects.filter(
                        id=specific_user_id,
                        is_superuser=True
                    ).values_list('id', flat=True)
                )
            else:
                superuser_ids = list(
                    User.objects.filter(
                        is_superuser=True
                    ).values_list('id', flat=True)
                )
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'Error fetching superuser IDs: {e}')
            )
            return
        
        if not superuser_ids:
            self.stdout.write(self.style.WARNING('No superusers found'))
            return
        
        self.stdout.write(
            self.style.SUCCESS(f'Found {len(superuser_ids)} superuser(s)')
        )
        
        # Get active businesses
        try:
            businesses = Business.objects.filter(is_active=True)
            business_count = businesses.count()
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'Error fetching businesses: {e}')
            )
            return
        
        if business_count == 0:
            self.stdout.write(self.style.WARNING('No active businesses found'))
            return
        
        self.stdout.write(
            self.style.SUCCESS(f'Found {business_count} active business(es)')
        )
        
        # Process each superuser
        created_count = 0
        updated_count = 0
        error_count = 0
        
        for user_id in superuser_ids:
            try:
                # Load user instance
                superuser = User.objects.get(id=user_id)
                user_email = getattr(superuser, 'email', f'User ID: {user_id}')
                
                self.stdout.write(f'\n{"="*60}')
                self.stdout.write(f'Processing: {user_email}')
                self.stdout.write(f'{"="*60}')
                
                # Ensure profile exists
                try:
                    profile, profile_created = UserProfile.objects.get_or_create(
                        user=superuser
                    )
                    if profile_created:
                        self.stdout.write(
                            self.style.SUCCESS(f'  ✓ Created UserProfile')
                        )
                except Exception as e:
                    self.stdout.write(
                        self.style.ERROR(f'  ✗ Failed to create profile: {e}')
                    )
                
                # Process each business
                for business in businesses:
                    try:
                        with transaction.atomic():
                            membership, created = BusinessMembership.objects.get_or_create(
                                user=superuser,
                                business=business,
                                defaults={
                                    'role': role,
                                    'is_active': True,
                                    'invitation_accepted': True,
                                    'all_locations_access': True,
                                    'permissions': self.get_default_permissions()
                                }
                            )
                            
                            if created:
                                created_count += 1
                                self.stdout.write(
                                    self.style.SUCCESS(
                                        f'  ✓ Created {role} membership for: {business.name}'
                                    )
                                )
                            else:
                                # Update existing membership
                                membership.role = role
                                membership.is_active = True
                                membership.all_locations_access = True
                                membership.invitation_accepted = True
                                
                                # Update permissions if empty or missing
                                if not membership.permissions:
                                    membership.permissions = self.get_default_permissions()
                                
                                membership.save()
                                updated_count += 1
                                self.stdout.write(
                                    self.style.WARNING(
                                        f'  ↻ Updated membership for: {business.name}'
                                    )
                                )
                    
                    except Exception as e:
                        error_count += 1
                        self.stdout.write(
                            self.style.ERROR(
                                f'  ✗ Error processing business {business.name}: {e}'
                            )
                        )
                        continue
            
            except User.DoesNotExist:
                error_count += 1
                self.stdout.write(
                    self.style.ERROR(f'User with ID {user_id} not found')
                )
                continue
            
            except Exception as e:
                error_count += 1
                self.stdout.write(
                    self.style.ERROR(
                        f'Error processing user ID {user_id}: {e}'
                    )
                )
                continue
        
        # Print summary
        self.stdout.write(f'\n{"="*60}')
        self.stdout.write(self.style.SUCCESS('SUMMARY'))
        self.stdout.write(f'{"="*60}')
        self.stdout.write(
            self.style.SUCCESS(f'✓ Created: {created_count} membership(s)')
        )
        self.stdout.write(
            self.style.WARNING(f'↻ Updated: {updated_count} membership(s)')
        )
        
        if error_count > 0:
            self.stdout.write(
                self.style.ERROR(f'✗ Errors: {error_count}')
            )
        
        self.stdout.write(
            self.style.SUCCESS(
                f'\nSuperusers now have {role} access to all businesses'
            )
        )