from django.core.management.base import BaseCommand
from users.models import RolePermission, DefaultRolePermission


class Command(BaseCommand):
    help = 'Set up comprehensive role-based permissions covering all system modules and actions'

    def handle(self, *args, **options):
        # Clear existing permissions
        RolePermission.objects.all().delete()
        DefaultRolePermission.objects.all().delete()
        
        self.stdout.write('Setting up comprehensive permissions...')
        
        # Define comprehensive default permissions for each role
        role_permissions = {
            'admin': {
                # Admin gets all permissions
                'dashboard': ['view', 'manage'],
                'users': ['view', 'create', 'edit', 'delete', 'manage', 'suspend', 'activate', 'verify', 'assign', 'reassign'],
                'clients': ['view', 'create', 'edit', 'delete', 'manage', 'assign', 'reassign', 'suspend', 'activate', 'verify', 'export', 'import'],
                'loans': ['view', 'create', 'edit', 'delete', 'approve', 'reject', 'manage', 'export', 'import', 'restore', 'permanently_delete'],
                'applications': ['view', 'create', 'edit', 'delete', 'approve', 'reject', 'manage', 'export', 'import'],
                'repayments': ['view', 'create', 'edit', 'delete', 'manage', 'verify', 'record_repayment', 'process_payment', 'adjust', 'reconcile'],
                'rollovers': ['view', 'create', 'edit', 'delete', 'approve', 'reject', 'manage'],
                
                # Reports - Admin can access all reports
                'reports': ['view', 'create', 'edit', 'delete', 'export', 'import', 'manage', 'generate', 'print'],
                'reports_loans_due': ['view', 'export', 'generate', 'print'],
                'reports_delinquent': ['view', 'export', 'generate', 'print'],
                'reports_arrears': ['view', 'export', 'generate', 'print'],
                'reports_processing_fees': ['view', 'export', 'generate', 'print'],
                'reports_interest_income': ['view', 'export', 'generate', 'print'],
                'reports_registration_fees': ['view', 'export', 'generate', 'print'],
                'reports_customer_requests': ['view', 'export', 'generate', 'print'],
                'reports_portfolio': ['view', 'export', 'generate', 'print'],
                'reports_analytics': ['view', 'export', 'generate', 'print'],
                
                # Documents & Media
                'documents': ['view', 'create', 'edit', 'delete', 'upload', 'download', 'share', 'manage', 'print'],
                'receipts': ['view', 'create', 'edit', 'delete', 'generate', 'print', 'download', 'share'],
                'statements': ['view', 'create', 'edit', 'delete', 'generate', 'print', 'download', 'share'],
                'media': ['view', 'create', 'edit', 'delete', 'upload', 'download', 'share', 'manage'],
                
                # Payment & Financial
                'payments': ['view', 'create', 'edit', 'delete', 'manage', 'process_payment', 'refund', 'adjust', 'reconcile'],
                'mpesa': ['view', 'create', 'edit', 'delete', 'manage', 'configure', 'monitor'],
                'transactions': ['view', 'create', 'edit', 'delete', 'manage', 'verify', 'reconcile', 'export'],
                
                # Portfolio & Assignment
                'portfolio': ['view', 'create', 'edit', 'delete', 'manage', 'assign', 'reassign', 'supervise'],
                'assignments': ['view', 'create', 'edit', 'delete', 'manage', 'assign', 'reassign'],
                'branches': ['view', 'create', 'edit', 'delete', 'manage', 'configure'],
                
                # System Administration
                'settings': ['view', 'create', 'edit', 'delete', 'manage', 'configure'],
                'notifications': ['view', 'create', 'edit', 'delete', 'manage', 'send_notification', 'send_email', 'send_sms'],
                'audit': ['view', 'export', 'manage', 'monitor'],
                'kyc': ['view', 'create', 'edit', 'delete', 'verify', 'approve', 'reject', 'manage'],
                'communications': ['view', 'create', 'edit', 'delete', 'manage', 'communicate', 'send_email', 'send_sms'],
                'backup': ['view', 'create', 'edit', 'delete', 'manage', 'backup', 'restore'],
                'system': ['view', 'create', 'edit', 'delete', 'manage', 'configure', 'monitor'],
                'maintenance': ['view', 'create', 'edit', 'delete', 'manage', 'maintain', 'configure'],
                
                # API & Integration
                'api': ['view', 'create', 'edit', 'delete', 'manage', 'api_access', 'configure'],
                'integrations': ['view', 'create', 'edit', 'delete', 'manage', 'integration_manage', 'webhook_manage'],
            },
            
            'team_leader': {
                # Team Leader gets management and oversight permissions
                'dashboard': ['view', 'manage'],
                'users': ['view', 'create', 'edit', 'manage', 'assign', 'reassign', 'verify'],
                'clients': ['view', 'create', 'edit', 'manage', 'assign', 'reassign', 'verify', 'export'],
                'loans': ['view', 'create', 'edit', 'approve', 'reject', 'manage', 'export'],
                'applications': ['view', 'create', 'edit', 'approve', 'reject', 'manage', 'export'],
                'repayments': ['view', 'create', 'edit', 'manage', 'verify', 'record_repayment', 'process_payment'],
                'rollovers': ['view', 'create', 'edit', 'approve', 'reject', 'manage'],
                
                # Reports - Team Leader can view and export most reports
                'reports': ['view', 'export', 'generate', 'print'],
                'reports_loans_due': ['view', 'export', 'generate', 'print'],
                'reports_delinquent': ['view', 'export', 'generate', 'print'],
                'reports_arrears': ['view', 'export', 'generate', 'print'],
                'reports_processing_fees': ['view', 'export', 'generate', 'print'],
                'reports_interest_income': ['view', 'export', 'generate', 'print'],
                'reports_registration_fees': ['view', 'export', 'generate', 'print'],
                'reports_customer_requests': ['view', 'export', 'generate', 'print'],
                'reports_portfolio': ['view', 'export', 'generate', 'print'],
                'reports_analytics': ['view', 'export', 'generate', 'print'],
                
                # Documents & Media
                'documents': ['view', 'create', 'edit', 'upload', 'download', 'share', 'print'],
                'receipts': ['view', 'create', 'edit', 'generate', 'print', 'download', 'share'],
                'statements': ['view', 'create', 'edit', 'generate', 'print', 'download', 'share'],
                'media': ['view', 'create', 'edit', 'upload', 'download', 'share'],
                
                # Payment & Financial
                'payments': ['view', 'create', 'edit', 'manage', 'process_payment', 'adjust'],
                'mpesa': ['view', 'monitor'],
                'transactions': ['view', 'create', 'edit', 'manage', 'verify', 'export'],
                
                # Portfolio & Assignment
                'portfolio': ['view', 'create', 'edit', 'manage', 'assign', 'reassign', 'supervise'],
                'assignments': ['view', 'create', 'edit', 'manage', 'assign', 'reassign'],
                'branches': ['view', 'edit'],
                
                # System Administration
                'settings': ['view', 'edit'],
                'notifications': ['view', 'create', 'edit', 'manage', 'send_notification', 'send_email', 'send_sms'],
                'audit': ['view', 'export'],
                'kyc': ['view', 'create', 'edit', 'verify', 'approve', 'reject', 'manage'],
                'communications': ['view', 'create', 'edit', 'manage', 'communicate', 'send_email', 'send_sms'],
                'backup': ['view'],
                'system': ['view'],
                'maintenance': ['view'],
                
                # API & Integration
                'api': ['view', 'api_access'],
                'integrations': ['view'],
            },
            
            'loan_officer': {
                # Loan Officer gets client and loan handling permissions
                'dashboard': ['view'],
                'users': ['view'],
                'clients': ['view', 'create', 'edit', 'verify', 'export'],
                'loans': ['view', 'create', 'edit', 'export'],
                'applications': ['view', 'create', 'edit', 'export'],
                'repayments': ['view', 'create', 'edit', 'record_repayment', 'process_payment'],
                'rollovers': ['view', 'create', 'edit'],
                
                # Reports - Loan Officer can view basic reports
                'reports': ['view', 'export', 'print'],
                'reports_loans_due': ['view', 'export', 'print'],
                'reports_delinquent': ['view', 'export', 'print'],
                'reports_arrears': ['view', 'export', 'print'],
                'reports_processing_fees': ['view', 'export', 'print'],
                'reports_interest_income': ['view', 'export', 'print'],
                'reports_registration_fees': ['view', 'export', 'print'],
                'reports_customer_requests': ['view', 'export', 'print'],
                'reports_portfolio': ['view', 'export', 'print'],
                'reports_analytics': ['view', 'export', 'print'],
                
                # Documents & Media
                'documents': ['view', 'create', 'edit', 'upload', 'download', 'print'],
                'receipts': ['view', 'create', 'edit', 'generate', 'print', 'download'],
                'statements': ['view', 'create', 'edit', 'generate', 'print', 'download'],
                'media': ['view', 'create', 'edit', 'upload', 'download'],
                
                # Payment & Financial
                'payments': ['view', 'create', 'edit', 'process_payment'],
                'mpesa': ['view'],
                'transactions': ['view', 'create', 'edit', 'verify'],
                
                # Portfolio & Assignment
                'portfolio': ['view'],
                'assignments': ['view'],
                'branches': ['view'],
                
                # System Administration
                'settings': ['view'],
                'notifications': ['view', 'send_notification', 'send_email', 'send_sms'],
                'audit': ['view'],
                'kyc': ['view', 'create', 'edit', 'verify'],
                'communications': ['view', 'create', 'edit', 'communicate', 'send_email', 'send_sms'],
                'backup': [],
                'system': [],
                'maintenance': [],
                
                # API & Integration
                'api': ['view'],
                'integrations': [],
            },
            
            'secretary': {
                # Secretary gets administrative and documentation permissions
                'dashboard': ['view'],
                'users': ['view'],
                'clients': ['view', 'create', 'edit', 'export'],
                'loans': ['view', 'export'],
                'applications': ['view', 'create', 'edit', 'export'],
                'repayments': ['view', 'create', 'edit'],
                'rollovers': ['view'],
                
                # Reports - Secretary can view and print reports
                'reports': ['view', 'export', 'print'],
                'reports_loans_due': ['view', 'export', 'print'],
                'reports_delinquent': ['view', 'export', 'print'],
                'reports_arrears': ['view', 'export', 'print'],
                'reports_processing_fees': ['view', 'export', 'print'],
                'reports_interest_income': ['view', 'export', 'print'],
                'reports_registration_fees': ['view', 'export', 'print'],
                'reports_customer_requests': ['view', 'export', 'print'],
                'reports_portfolio': ['view', 'export', 'print'],
                'reports_analytics': ['view', 'export', 'print'],
                
                # Documents & Media - Secretary has full access
                'documents': ['view', 'create', 'edit', 'delete', 'upload', 'download', 'share', 'print'],
                'receipts': ['view', 'create', 'edit', 'delete', 'generate', 'print', 'download', 'share'],
                'statements': ['view', 'create', 'edit', 'delete', 'generate', 'print', 'download', 'share'],
                'media': ['view', 'create', 'edit', 'delete', 'upload', 'download', 'share'],
                
                # Payment & Financial
                'payments': ['view', 'create', 'edit'],
                'mpesa': ['view'],
                'transactions': ['view', 'create', 'edit'],
                
                # Portfolio & Assignment
                'portfolio': ['view'],
                'assignments': ['view'],
                'branches': ['view'],
                
                # System Administration
                'settings': ['view'],
                'notifications': ['view', 'send_notification', 'send_email', 'send_sms'],
                'audit': ['view'],
                'kyc': ['view', 'create', 'edit'],
                'communications': ['view', 'create', 'edit', 'communicate', 'send_email', 'send_sms'],
                'backup': [],
                'system': [],
                'maintenance': [],
                
                # API & Integration
                'api': ['view'],
                'integrations': [],
            },
            
            'borrower': {
                # Borrowers have very limited access
                'dashboard': ['view'],
                'users': [],
                'clients': ['view'],
                'loans': ['view'],
                'applications': ['view', 'create'],
                'repayments': ['view'],
                'rollovers': ['view', 'create'],
                
                # Reports - Borrowers can only view their own data
                'reports': [],
                'reports_loans_due': [],
                'reports_delinquent': [],
                'reports_arrears': [],
                'reports_processing_fees': [],
                'reports_interest_income': [],
                'reports_registration_fees': [],
                'reports_customer_requests': [],
                'reports_portfolio': [],
                'reports_analytics': [],
                
                # Documents & Media - Limited access
                'documents': ['view', 'download'],
                'receipts': ['view', 'download'],
                'statements': ['view', 'download'],
                'media': ['view', 'download'],
                
                # Payment & Financial
                'payments': ['view'],
                'mpesa': [],
                'transactions': ['view'],
                
                # Portfolio & Assignment
                'portfolio': [],
                'assignments': [],
                'branches': [],
                
                # System Administration
                'settings': [],
                'notifications': ['view'],
                'audit': [],
                'kyc': ['view'],
                'communications': ['view'],
                'backup': [],
                'system': [],
                'maintenance': [],
                
                # API & Integration
                'api': [],
                'integrations': [],
            }
        }
        
        # Create permissions for each role
        for role, modules in role_permissions.items():
            for module, actions in modules.items():
                for action in actions:
                    # Create RolePermission
                    RolePermission.objects.get_or_create(
                        role=role,
                        module=module,
                        action=action,
                        defaults={'is_allowed': True}
                    )
                    
                    # Create DefaultRolePermission
                    DefaultRolePermission.objects.get_or_create(
                        role=role,
                        module=module,
                        action=action,
                        defaults={
                            'is_allowed': True,
                            'description': f'Default permission for {role} to {action} {module}'
                        }
                    )
        
        # Create denied permissions for actions not explicitly allowed
        all_modules = [choice[0] for choice in RolePermission.MODULE_CHOICES]
        all_actions = [choice[0] for choice in RolePermission.ACTION_CHOICES]
        
        for role in ['admin', 'team_leader', 'loan_officer', 'secretary', 'borrower']:
            for module in all_modules:
                for action in all_actions:
                    # Only create if it doesn't exist
                    if not RolePermission.objects.filter(role=role, module=module, action=action).exists():
                        RolePermission.objects.create(
                            role=role,
                            module=module,
                            action=action,
                            is_allowed=False
                        )
                    
                    if not DefaultRolePermission.objects.filter(role=role, module=module, action=action).exists():
                        DefaultRolePermission.objects.create(
                            role=role,
                            module=module,
                            action=action,
                            is_allowed=False,
                            description=f'Default permission for {role} to {action} {module}'
                        )
        
        self.stdout.write(
            self.style.SUCCESS(
                f'Successfully created comprehensive permissions for {len(role_permissions)} roles '
                f'covering {len(all_modules)} modules and {len(all_actions)} actions'
            )
        )
