"""
Role Template Management Views for Granular Permissions System
"""
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.db import transaction
from django.views.decorators.http import require_http_methods
from django.core.paginator import Paginator
from django.db.models import Q, Count
import json
import logging

from .models import CustomUser
from .enhanced_permissions_models import PagePermission, RolePermissionTemplate, UserPagePermission
from .services import RolePermissionTemplateManager, PagePermissionManager
from .decorators import admin_required

logger = logging.getLogger(__name__)


@login_required
@admin_required
def role_template_configuration(request):
    """
    Main role template configuration interface
    Build admin interface for setting default role permissions
    """
    template_manager = RolePermissionTemplateManager()
    
    # Get all available roles
    roles = CustomUser.ROLE_CHOICES
    
    # Get all page permissions grouped by page
    page_permissions = PagePermission.objects.filter(is_active=True).order_by(
        'page_name', 'category', 'action_name'
    )
    
    # Group permissions by page
    permissions_by_page = {}
    for perm in page_permissions:
        if perm.page_name not in permissions_by_page:
            permissions_by_page[perm.page_name] = {}
        if perm.category not in permissions_by_page[perm.page_name]:
            permissions_by_page[perm.page_name][perm.category] = []
        permissions_by_page[perm.page_name][perm.category].append(perm)
    
    # Get current role templates for each role
    role_templates = {}
    for role_code, role_name in roles:
        role_templates[role_code] = template_manager.get_role_template(role_code)
    
    # Get statistics for each role
    role_stats = {}
    for role_code, role_name in roles:
        templates = RolePermissionTemplate.objects.filter(role=role_code)
        allowed_count = templates.filter(is_allowed=True).count()
        total_count = templates.count()
        
        role_stats[role_code] = {
            'name': role_name,
            'allowed_permissions': allowed_count,
            'total_permissions': total_count,
            'percentage': round((allowed_count / total_count * 100) if total_count > 0 else 0, 1)
        }
    
    context = {
        'roles': roles,
        'permissions_by_page': permissions_by_page,
        'role_templates': role_templates,
        'role_stats': role_stats,
        'total_permissions': page_permissions.count(),
        'page_names': list(permissions_by_page.keys()),
    }
    
    return render(request, 'users/role_template_configuration.html', context)


@login_required
@admin_required
def save_role_template(request):
    """
    Save role template configuration
    Create permission matrix UI for easy role configuration
    """
    if request.method != 'POST':
        return JsonResponse({'success': False, 'error': 'Invalid request method'})
    
    try:
        data = json.loads(request.body)
        role = data.get('role')
        permissions = data.get('permissions', {})
        
        if not role or role not in dict(CustomUser.ROLE_CHOICES):
            return JsonResponse({'success': False, 'error': 'Invalid role'})
        
        template_manager = RolePermissionTemplateManager()
        
        # Set role defaults
        result = template_manager.set_role_defaults(
            role=role,
            permissions_dict=permissions,
            created_by=request.user
        )
        
        if result['success']:
            messages.success(
                request, 
                f"Role template for {dict(CustomUser.ROLE_CHOICES)[role]} updated successfully. "
                f"{result['created_permissions']} permissions created, "
                f"{result['updated_permissions']} permissions updated."
            )
            
            return JsonResponse({
                'success': True,
                'message': 'Role template saved successfully',
                'stats': {
                    'created': result['created_permissions'],
                    'updated': result['updated_permissions'],
                    'total': result['total_permissions']
                }
            })
        else:
            return JsonResponse({
                'success': False,
                'error': result.get('error', 'Unknown error occurred'),
                'errors': result.get('errors', [])
            })
            
    except json.JSONDecodeError:
        return JsonResponse({'success': False, 'error': 'Invalid JSON data'})
    except Exception as e:
        logger.error(f"Error saving role template: {e}")
        return JsonResponse({'success': False, 'error': str(e)})


@login_required
@admin_required
def bulk_permission_assignment(request):
    """
    Implement bulk permission assignment for roles
    """
    if request.method != 'POST':
        return JsonResponse({'success': False, 'error': 'Invalid request method'})
    
    try:
        data = json.loads(request.body)
        action = data.get('action')  # 'grant_all', 'revoke_all', 'copy_role'
        target_roles = data.get('roles', [])
        source_role = data.get('source_role')
        page_filter = data.get('page_filter')
        category_filter = data.get('category_filter')
        
        template_manager = RolePermissionTemplateManager()
        results = []
        
        for role in target_roles:
            if role not in dict(CustomUser.ROLE_CHOICES):
                continue
                
            if action == 'grant_all':
                # Grant all permissions for specified filters
                permissions_dict = {}
                page_permissions = PagePermission.objects.filter(is_active=True)
                
                if page_filter:
                    page_permissions = page_permissions.filter(page_name=page_filter)
                if category_filter:
                    page_permissions = page_permissions.filter(category=category_filter)
                
                for perm in page_permissions:
                    if perm.page_name not in permissions_dict:
                        permissions_dict[perm.page_name] = {}
                    permissions_dict[perm.page_name][perm.action_code] = True
                
                result = template_manager.set_role_defaults(
                    role=role,
                    permissions_dict=permissions_dict,
                    created_by=request.user
                )
                results.append({'role': role, 'result': result})
                
            elif action == 'revoke_all':
                # Revoke all permissions for specified filters
                permissions_dict = {}
                page_permissions = PagePermission.objects.filter(is_active=True)
                
                if page_filter:
                    page_permissions = page_permissions.filter(page_name=page_filter)
                if category_filter:
                    page_permissions = page_permissions.filter(category=category_filter)
                
                for perm in page_permissions:
                    if perm.page_name not in permissions_dict:
                        permissions_dict[perm.page_name] = {}
                    permissions_dict[perm.page_name][perm.action_code] = False
                
                result = template_manager.set_role_defaults(
                    role=role,
                    permissions_dict=permissions_dict,
                    created_by=request.user
                )
                results.append({'role': role, 'result': result})
                
            elif action == 'copy_role' and source_role:
                # Copy permissions from source role
                source_template = template_manager.get_role_template(source_role)
                
                result = template_manager.set_role_defaults(
                    role=role,
                    permissions_dict=source_template,
                    created_by=request.user
                )
                results.append({'role': role, 'result': result})
        
        # Calculate summary statistics
        total_created = sum(r['result']['created_permissions'] for r in results if r['result']['success'])
        total_updated = sum(r['result']['updated_permissions'] for r in results if r['result']['success'])
        successful_roles = [r['role'] for r in results if r['result']['success']]
        failed_roles = [r['role'] for r in results if not r['result']['success']]
        
        if successful_roles:
            messages.success(
                request,
                f"Bulk operation completed for {len(successful_roles)} roles. "
                f"{total_created} permissions created, {total_updated} permissions updated."
            )
        
        if failed_roles:
            messages.error(
                request,
                f"Bulk operation failed for {len(failed_roles)} roles: {', '.join(failed_roles)}"
            )
        
        return JsonResponse({
            'success': len(successful_roles) > 0,
            'results': results,
            'summary': {
                'successful_roles': successful_roles,
                'failed_roles': failed_roles,
                'total_created': total_created,
                'total_updated': total_updated
            }
        })
        
    except json.JSONDecodeError:
        return JsonResponse({'success': False, 'error': 'Invalid JSON data'})
    except Exception as e:
        logger.error(f"Error in bulk permission assignment: {e}")
        return JsonResponse({'success': False, 'error': str(e)})


@login_required
@admin_required
def role_comparison(request):
    """
    Add role comparison and cloning functionality
    """
    template_manager = RolePermissionTemplateManager()
    
    # Get comparison parameters
    role1 = request.GET.get('role1')
    role2 = request.GET.get('role2')
    
    if not role1 or not role2:
        # Show role selection interface
        roles = CustomUser.ROLE_CHOICES
        return render(request, 'users/role_comparison_select.html', {'roles': roles})
    
    # Get templates for both roles
    template1 = template_manager.get_role_template(role1)
    template2 = template_manager.get_role_template(role2)
    
    # Compare permissions
    comparison_data = {}
    all_pages = set(template1.keys()) | set(template2.keys())
    
    for page_name in all_pages:
        page1_perms = template1.get(page_name, {})
        page2_perms = template2.get(page_name, {})
        all_actions = set(page1_perms.keys()) | set(page2_perms.keys())
        
        comparison_data[page_name] = {}
        
        for action_code in all_actions:
            perm1 = page1_perms.get(action_code, {})
            perm2 = page2_perms.get(action_code, {})
            
            allowed1 = perm1.get('is_allowed', False)
            allowed2 = perm2.get('is_allowed', False)
            
            # Determine comparison status
            if allowed1 and allowed2:
                status = 'both'
            elif allowed1 and not allowed2:
                status = 'role1_only'
            elif not allowed1 and allowed2:
                status = 'role2_only'
            else:
                status = 'neither'
            
            comparison_data[page_name][action_code] = {
                'action_name': perm1.get('action_name') or perm2.get('action_name', action_code),
                'category': perm1.get('category') or perm2.get('category', 'unknown'),
                'role1_allowed': allowed1,
                'role2_allowed': allowed2,
                'status': status
            }
    
    # Calculate statistics
    stats = {
        'total_permissions': 0,
        'both_allowed': 0,
        'role1_only': 0,
        'role2_only': 0,
        'neither_allowed': 0
    }
    
    for page_perms in comparison_data.values():
        for perm_data in page_perms.values():
            stats['total_permissions'] += 1
            stats[perm_data['status']] += 1
    
    context = {
        'role1': role1,
        'role2': role2,
        'role1_name': dict(CustomUser.ROLE_CHOICES)[role1],
        'role2_name': dict(CustomUser.ROLE_CHOICES)[role2],
        'comparison_data': comparison_data,
        'stats': stats,
        'roles': CustomUser.ROLE_CHOICES
    }
    
    return render(request, 'users/role_comparison.html', context)


@login_required
@admin_required
def clone_role_template(request):
    """
    Clone role template from one role to another
    """
    if request.method != 'POST':
        return JsonResponse({'success': False, 'error': 'Invalid request method'})
    
    try:
        data = json.loads(request.body)
        source_role = data.get('source_role')
        target_role = data.get('target_role')
        overwrite = data.get('overwrite', False)
        
        if not source_role or not target_role:
            return JsonResponse({'success': False, 'error': 'Source and target roles are required'})
        
        if source_role not in dict(CustomUser.ROLE_CHOICES) or target_role not in dict(CustomUser.ROLE_CHOICES):
            return JsonResponse({'success': False, 'error': 'Invalid role specified'})
        
        template_manager = RolePermissionTemplateManager()
        
        # Get source role template
        source_template = template_manager.get_role_template(source_role)
        
        if not source_template:
            return JsonResponse({'success': False, 'error': 'Source role has no template'})
        
        # Convert template format for set_role_defaults
        permissions_dict = {}
        for page_name, actions in source_template.items():
            permissions_dict[page_name] = {}
            for action_code, perm_data in actions.items():
                permissions_dict[page_name][action_code] = perm_data['is_allowed']
        
        # Apply to target role
        result = template_manager.set_role_defaults(
            role=target_role,
            permissions_dict=permissions_dict,
            created_by=request.user
        )
        
        if result['success']:
            messages.success(
                request,
                f"Successfully cloned {dict(CustomUser.ROLE_CHOICES)[source_role]} template to "
                f"{dict(CustomUser.ROLE_CHOICES)[target_role]}. "
                f"{result['created_permissions']} permissions created, "
                f"{result['updated_permissions']} permissions updated."
            )
            
            return JsonResponse({
                'success': True,
                'message': 'Role template cloned successfully',
                'stats': {
                    'created': result['created_permissions'],
                    'updated': result['updated_permissions'],
                    'total': result['total_permissions']
                }
            })
        else:
            return JsonResponse({
                'success': False,
                'error': result.get('error', 'Failed to clone role template'),
                'errors': result.get('errors', [])
            })
            
    except json.JSONDecodeError:
        return JsonResponse({'success': False, 'error': 'Invalid JSON data'})
    except Exception as e:
        logger.error(f"Error cloning role template: {e}")
        return JsonResponse({'success': False, 'error': str(e)})


@login_required
@admin_required
def get_role_template_data(request, role):
    """
    Get role template data for AJAX requests
    """
    if role not in dict(CustomUser.ROLE_CHOICES):
        return JsonResponse({'success': False, 'error': 'Invalid role'})
    
    try:
        template_manager = RolePermissionTemplateManager()
        template_data = template_manager.get_role_template(role)
        
        # Get statistics
        templates = RolePermissionTemplate.objects.filter(role=role)
        allowed_count = templates.filter(is_allowed=True).count()
        total_count = templates.count()
        
        return JsonResponse({
            'success': True,
            'role': role,
            'role_name': dict(CustomUser.ROLE_CHOICES)[role],
            'template_data': template_data,
            'stats': {
                'allowed_permissions': allowed_count,
                'total_permissions': total_count,
                'percentage': round((allowed_count / total_count * 100) if total_count > 0 else 0, 1)
            }
        })
        
    except Exception as e:
        logger.error(f"Error getting role template data for {role}: {e}")
        return JsonResponse({'success': False, 'error': str(e)})


@login_required
@admin_required
def permission_matrix_view(request):
    """
    Create permission matrix UI for easy role configuration
    """
    # Get all roles and permissions
    roles = CustomUser.ROLE_CHOICES
    page_permissions = PagePermission.objects.filter(is_active=True).order_by(
        'page_name', 'category', 'action_name'
    )
    
    # Build permission matrix
    matrix_data = {}
    
    # Initialize matrix structure
    for perm in page_permissions:
        page_key = f"{perm.page_name}_{perm.action_code}"
        matrix_data[page_key] = {
            'permission': perm,
            'roles': {}
        }
        
        # Get role permissions for this page permission
        for role_code, role_name in roles:
            try:
                role_template = RolePermissionTemplate.objects.get(
                    role=role_code,
                    page_permission=perm
                )
                matrix_data[page_key]['roles'][role_code] = {
                    'allowed': role_template.is_allowed,
                    'can_override': role_template.can_override,
                    'priority': role_template.priority
                }
            except RolePermissionTemplate.DoesNotExist:
                matrix_data[page_key]['roles'][role_code] = {
                    'allowed': False,
                    'can_override': True,
                    'priority': 0
                }
    
    # Group by page for better organization
    pages_data = {}
    for key, data in matrix_data.items():
        page_name = data['permission'].page_name
        if page_name not in pages_data:
            pages_data[page_name] = []
        pages_data[page_name].append(data)
    
    context = {
        'roles': roles,
        'pages_data': pages_data,
        'matrix_data': matrix_data,
        'total_permissions': len(matrix_data),
        'total_roles': len(roles)
    }
    
    return render(request, 'users/permission_matrix.html', context)


@login_required
@admin_required
def apply_role_template_to_user(request, user_id):
    """
    Apply role template to a specific user
    """
    user = get_object_or_404(CustomUser, id=user_id)
    
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            role_template = data.get('role_template', user.role)
            update_existing = data.get('update_existing', False)
            
            template_manager = RolePermissionTemplateManager()
            result = template_manager.apply_role_template_to_user(
                user=user,
                role_template=role_template,
                update_existing=update_existing
            )
            
            if result['success']:
                messages.success(
                    request,
                    f"Role template applied successfully to {user.get_full_name()}. "
                    f"{result['permissions_applied']} permissions applied."
                )
                
                return JsonResponse({
                    'success': True,
                    'message': 'Role template applied successfully',
                    'stats': {
                        'permissions_applied': result['permissions_applied'],
                        'permissions_skipped': result['permissions_skipped']
                    }
                })
            else:
                return JsonResponse({
                    'success': False,
                    'error': result.get('error', 'Failed to apply role template'),
                    'errors': result.get('errors', [])
                })
                
        except json.JSONDecodeError:
            return JsonResponse({'success': False, 'error': 'Invalid JSON data'})
        except Exception as e:
            logger.error(f"Error applying role template to user {user_id}: {e}")
            return JsonResponse({'success': False, 'error': str(e)})
    
    # GET request - show template application form
    template_manager = RolePermissionTemplateManager()
    available_roles = CustomUser.ROLE_CHOICES
    
    # Get current user permissions summary
    permission_manager = PagePermissionManager()
    current_permissions = permission_manager.get_permission_summary(user, 'all')
    
    context = {
        'user': user,
        'available_roles': available_roles,
        'current_permissions': current_permissions,
        'current_role_template': template_manager.get_role_template(user.role)
    }
    
    return render(request, 'users/apply_role_template.html', context)


@login_required
@admin_required
def bulk_apply_role_templates(request):
    """
    Bulk apply role templates to multiple users
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            user_ids = data.get('user_ids', [])
            role_template = data.get('role_template')
            update_existing = data.get('update_existing', False)
            
            if not user_ids or not role_template:
                return JsonResponse({
                    'success': False,
                    'error': 'User IDs and role template are required'
                })
            
            template_manager = RolePermissionTemplateManager()
            result = template_manager.bulk_update_users_with_template(
                user_ids=user_ids,
                role=role_template,
                update_existing=update_existing
            )
            
            if result['success']:
                messages.success(
                    request,
                    f"Role template applied to {result['users_processed']} users. "
                    f"{result['permissions_applied']} permissions applied."
                )
                
                return JsonResponse({
                    'success': True,
                    'message': 'Role templates applied successfully',
                    'stats': {
                        'users_processed': result['users_processed'],
                        'permissions_applied': result['permissions_applied'],
                        'permissions_skipped': result['permissions_skipped']
                    }
                })
            else:
                return JsonResponse({
                    'success': False,
                    'error': result.get('error', 'Failed to apply role templates'),
                    'errors': result.get('errors', [])
                })
                
        except json.JSONDecodeError:
            return JsonResponse({'success': False, 'error': 'Invalid JSON data'})
        except Exception as e:
            logger.error(f"Error in bulk role template application: {e}")
            return JsonResponse({'success': False, 'error': str(e)})
    
    # GET request - show bulk application form
    staff_users = CustomUser.objects.filter(
        role__in=['admin', 'team_leader', 'loan_officer', 'secretary', 'auditor']
    ).order_by('role', 'first_name', 'last_name')
    
    # Group users by role
    users_by_role = {}
    for user in staff_users:
        if user.role not in users_by_role:
            users_by_role[user.role] = []
        users_by_role[user.role].append(user)
    
    context = {
        'staff_users': staff_users,
        'users_by_role': users_by_role,
        'available_roles': CustomUser.ROLE_CHOICES,
        'total_users': staff_users.count()
    }
    
    return render(request, 'users/bulk_apply_role_templates.html', context)


@login_required
@admin_required
def resolve_permission_conflicts(request, user_id):
    """
    Resolve permission conflicts for a user
    """
    user = get_object_or_404(CustomUser, id=user_id)
    
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            conflicts = data.get('conflicts', [])
            
            template_manager = RolePermissionTemplateManager()
            resolved_conflicts = []
            
            for conflict_data in conflicts:
                permission_id = conflict_data.get('permission_id')
                resolution_action = conflict_data.get('action')  # 'keep_custom', 'use_role', 'remove_custom'
                
                try:
                    page_permission = PagePermission.objects.get(id=permission_id)
                    
                    # Get current permissions
                    role_template = template_manager.get_role_template(user.role)
                    role_permission = role_template.get(page_permission.page_name, {}).get(
                        page_permission.action_code, {}
                    ).get('is_allowed', False)
                    
                    try:
                        custom_perm = UserPagePermission.objects.get(
                            user=user,
                            page_permission=page_permission
                        )
                        custom_permission = custom_perm.is_allowed
                    except UserPagePermission.DoesNotExist:
                        custom_permission = None
                    
                    # Resolve based on action
                    if resolution_action == 'use_role':
                        # Remove custom permission, use role default
                        UserPagePermission.objects.filter(
                            user=user,
                            page_permission=page_permission
                        ).delete()
                        
                        resolved_conflicts.append({
                            'permission_id': permission_id,
                            'action': 'used_role_default',
                            'final_permission': role_permission
                        })
                        
                    elif resolution_action == 'keep_custom' and custom_permission is not None:
                        # Keep existing custom permission
                        resolved_conflicts.append({
                            'permission_id': permission_id,
                            'action': 'kept_custom',
                            'final_permission': custom_permission
                        })
                        
                    elif resolution_action == 'remove_custom':
                        # Remove custom permission
                        UserPagePermission.objects.filter(
                            user=user,
                            page_permission=page_permission
                        ).delete()
                        
                        resolved_conflicts.append({
                            'permission_id': permission_id,
                            'action': 'removed_custom',
                            'final_permission': role_permission
                        })
                        
                except PagePermission.DoesNotExist:
                    continue
            
            # Invalidate user's permission cache
            PagePermissionManager().invalidate_user_cache(str(user.id))
            
            messages.success(
                request,
                f"Resolved {len(resolved_conflicts)} permission conflicts for {user.get_full_name()}"
            )
            
            return JsonResponse({
                'success': True,
                'message': 'Permission conflicts resolved successfully',
                'resolved_conflicts': resolved_conflicts
            })
            
        except json.JSONDecodeError:
            return JsonResponse({'success': False, 'error': 'Invalid JSON data'})
        except Exception as e:
            logger.error(f"Error resolving permission conflicts for user {user_id}: {e}")
            return JsonResponse({'success': False, 'error': str(e)})
    
    # GET request - show conflicts resolution interface
    template_manager = RolePermissionTemplateManager()
    permission_manager = PagePermissionManager()
    
    # Get role template
    role_template = template_manager.get_role_template(user.role)
    
    # Get user's custom permissions
    custom_permissions = UserPagePermission.objects.filter(user=user).select_related('page_permission')
    
    # Find conflicts
    conflicts = []
    for custom_perm in custom_permissions:
        page_name = custom_perm.page_permission.page_name
        action_code = custom_perm.page_permission.action_code
        
        role_perm_data = role_template.get(page_name, {}).get(action_code, {})
        role_permission = role_perm_data.get('is_allowed', False)
        can_override = role_perm_data.get('can_override', True)
        
        if custom_perm.is_allowed != role_permission:
            conflicts.append({
                'permission': custom_perm.page_permission,
                'custom_permission': custom_perm.is_allowed,
                'role_permission': role_permission,
                'can_override': can_override,
                'conflict_type': 'different_values'
            })
        elif not can_override:
            conflicts.append({
                'permission': custom_perm.page_permission,
                'custom_permission': custom_perm.is_allowed,
                'role_permission': role_permission,
                'can_override': can_override,
                'conflict_type': 'override_not_allowed'
            })
    
    context = {
        'user': user,
        'conflicts': conflicts,
        'total_conflicts': len(conflicts),
        'role_template': role_template
    }
    
    return render(request, 'users/resolve_permission_conflicts.html', context)


@login_required
@admin_required
def create_rollback_point(request):
    """
    Create a rollback point for role template changes
    """
    if request.method != 'POST':
        return JsonResponse({'success': False, 'error': 'Invalid request method'})
    
    try:
        data = json.loads(request.body)
        role = data.get('role')
        
        if not role or role not in dict(CustomUser.ROLE_CHOICES):
            return JsonResponse({'success': False, 'error': 'Invalid role'})
        
        template_manager = RolePermissionTemplateManager()
        rollback_id = template_manager.create_template_rollback_point(role)
        
        if rollback_id:
            return JsonResponse({
                'success': True,
                'rollback_id': rollback_id,
                'message': f'Rollback point created for {dict(CustomUser.ROLE_CHOICES)[role]}'
            })
        else:
            return JsonResponse({
                'success': False,
                'error': 'Failed to create rollback point'
            })
            
    except json.JSONDecodeError:
        return JsonResponse({'success': False, 'error': 'Invalid JSON data'})
    except Exception as e:
        logger.error(f"Error creating rollback point: {e}")
        return JsonResponse({'success': False, 'error': str(e)})


@login_required
@admin_required
def rollback_template_changes(request):
    """
    Rollback role template changes
    """
    if request.method != 'POST':
        return JsonResponse({'success': False, 'error': 'Invalid request method'})
    
    try:
        data = json.loads(request.body)
        rollback_id = data.get('rollback_id')
        
        if not rollback_id:
            return JsonResponse({'success': False, 'error': 'Rollback ID is required'})
        
        template_manager = RolePermissionTemplateManager()
        result = template_manager.rollback_template_changes(rollback_id)
        
        if result['success']:
            messages.success(
                request,
                f"Successfully rolled back {dict(CustomUser.ROLE_CHOICES)[result['role']]} "
                f"template to {result['rollback_date']}. "
                f"{result['permissions_restored']} permissions restored."
            )
            
            return JsonResponse({
                'success': True,
                'message': 'Template changes rolled back successfully',
                'role': result['role'],
                'rollback_date': result['rollback_date'],
                'permissions_restored': result['permissions_restored']
            })
        else:
            return JsonResponse({
                'success': False,
                'error': result.get('error', 'Failed to rollback template changes')
            })
            
    except json.JSONDecodeError:
        return JsonResponse({'success': False, 'error': 'Invalid JSON data'})
    except Exception as e:
        logger.error(f"Error rolling back template changes: {e}")
        return JsonResponse({'success': False, 'error': str(e)})