# core/mixins.py
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect
from django.contrib import messages

class RoleRequiredMixin:
    """Mixin to restrict access based on role"""
    required_role = None
    required_roles = []
    
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return redirect('login')
        
        if request.user.is_superuser:
            return super().dispatch(request, *args, **kwargs)
        
        if not hasattr(request.user, 'staff_profile'):
            messages.error(request, "You don't have a staff profile.")
            return redirect('home')
        
        staff = request.user.staff_profile
        
        if self.required_role and staff.role != self.required_role:
            raise PermissionDenied
        
        if self.required_roles and staff.role not in self.required_roles:
            raise PermissionDenied
        
        return super().dispatch(request, *args, **kwargs)

class SchoolRequiredMixin:
    """Mixin to ensure user belongs to a school"""
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return redirect('login')
        
        if request.user.is_superuser:
            return super().dispatch(request, *args, **kwargs)
        
        if hasattr(request.user, 'staff_profile') and request.user.staff_profile.school:
            return super().dispatch(request, *args, **kwargs)
        
        messages.error(request, "You are not associated with any school.")
        return redirect('home')