"""
Setup Source User permissions and groups.

Creates a dedicated 'PX Source User' group with limited permissions
to ensure source users can only access their designated features.
"""
from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q


class Command(BaseCommand):
    help = 'Setup Source User permissions and groups for access control'

    def handle(self, **options):
        self.stdout.write(self.style.NOTICE('Setting up Source User permissions...'))
        
        # Create Source User group
        source_user_group, created = Group.objects.get_or_create(name='PX Source User')
        
        if created:
            self.stdout.write(self.style.SUCCESS('✓ Created "PX Source User" group'))
        else:
            self.stdout.write(self.style.NOTICE('✓ Found existing "PX Source User" group'))
        
        # Get permissions for Complaint and Inquiry
        permissions = []
        permission_names = []
        
        # Complaint permissions (only create and view their own)
        complaint_perms = [
            ('complaints', 'add_complaint'),
            ('complaints', 'view_complaint'),
            ('complaints', 'change_complaint'),
        ]
        
        # Inquiry permissions
        inquiry_perms = [
            ('complaints', 'add_inquiry'),
            ('complaints', 'view_inquiry'),
            ('complaints', 'change_inquiry'),
        ]
        
        # Collect all permissions
        all_perms = complaint_perms + inquiry_perms
        
        for app_label, codename in all_perms:
            try:
                perm = Permission.objects.get(
                    content_type__app_label=app_label,
                    codename=codename
                )
                permissions.append(perm)
                permission_names.append(f"{app_label}.{codename}")
            except Permission.DoesNotExist:
                self.stdout.write(
                    self.style.WARNING(f'⚠ Permission {app_label}.{codename} not found')
                )
        
        # Set permissions for the group
        source_user_group.permissions.set(permissions)
        
        self.stdout.write(
            self.style.SUCCESS(
                f'✓ Assigned {len(permissions)} permissions to "PX Source User" group'
            )
        )
        
        # List assigned permissions
        self.stdout.write(self.style.NOTICE('\nAssigned permissions:'))
        for perm_name in permission_names:
            self.stdout.write(f'  - {perm_name}')
        
        # Create a warning about what source users CANNOT do
        self.stdout.write(self.style.WARNING('\n⚠ Source users are RESTRICTED from:'))
        self.stdout.write('  - Admin pages (/admin/)')
        self.stdout.write('  - Analytics dashboards')
        self.stdout.write('  - Configuration settings')
        self.stdout.write('  - Staff management')
        self.stdout.write('  - Source management (creating/editing sources)')
        self.stdout.write('  - User management')
        self.stdout.write('  - Onboarding management')
        
        self.stdout.write(
            self.style.SUCCESS(
                '\n✅ Source User permissions setup complete!\n'
            )
        )
        
        # Instructions for assigning users to the group
        self.stdout.write(self.style.NOTICE('To assign a user to the Source User group:'))
        self.stdout.write('  1. Go to Admin → Authentication and Authorization → Users')
        self.stdout.write('  2. Select the user')
        self.stdout.write('  3. Add "PX Source User" to their groups')
        self.stdout.write('  4. Also create a SourceUser profile for them in PX Sources')
