# -*- coding: utf-8 -*-
"""
Django Management Command to Setup Permissions and Roles

This command creates default permissions and roles for the accounts app.
"""

from django.core.management.base import BaseCommand
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from apps.accounts.models import Role, User
from apps.accounts.permissions import create_default_permissions, setup_default_roles


class Command(BaseCommand):
    help = 'Setup default permissions and roles for the accounts app'

    def add_arguments(self, parser):
        parser.add_argument(
            '--create-superuser',
            action='store_true',
            help='Create a superuser with super_admin role',
        )
        parser.add_argument(
            '--email',
            type=str,
            help='Email for the superuser',
        )
        parser.add_argument(
            '--password',
            type=str,
            help='Password for the superuser',
        )

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Setting up permissions and roles...'))
        
        # Create default permissions
        self.stdout.write('Creating default permissions...')
        create_default_permissions()
        
        # Setup default roles
        self.stdout.write('Setting up default roles...')
        setup_default_roles()
        
        # Create superuser if requested
        if options['create_superuser']:
            self.create_superuser(options.get('email'), options.get('password'))
        
        self.stdout.write(self.style.SUCCESS('Setup completed successfully!'))
    
    def create_superuser(self, email, password):
        """Create a superuser with super_admin role."""
        if not email:
            email = input('Email: ')
        if not password:
            password = input('Password: ')
        
        try:
            user = User.objects.create_superuser(
                email=email,
                password=password,
                username=email.split('@')[0]
            )
            
            # Get or create super_admin role
            super_admin_role, created = Role.objects.get_or_create(
                code='super_admin',
                defaults={
                    'name': 'Super Administrator',
                    'description': 'Has full access to all system features',
                    'role_type': 'system',
                    'level': 1,
                    'is_active': True
                }
            )
            
            # Assign super_admin role to user
            from apps.accounts.models import UserRole
            user_role, created = UserRole.objects.get_or_create(
                user=user,
                role=super_admin_role,
                defaults={
                    'assigned_by': user,
                    'is_active': True
                }
            )
            
            self.stdout.write(
                self.style.SUCCESS(f'Superuser created: {email}')
            )
            
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'Error creating superuser: {str(e)}')
            )
