from django.http import HttpResponseForbidden
from django.shortcuts import redirect
from django.urls import reverse
from django.contrib import messages


class AdminAccessMiddleware:
    """Middleware to restrict Django admin access to only admin users"""
    
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Check if the request is for admin interface
        if request.path.startswith('/admin/'):
            # Allow login page and static files
            if (request.path == '/admin/' or 
                request.path == '/admin/login/' or 
                request.path.startswith('/admin/jsi18n/') or
                request.path.startswith('/static/')):
                return self.get_response(request)
            
            # Check if user is authenticated and is admin
            if request.user.is_authenticated:
                if not request.user.is_admin and not request.user.is_superuser:
                    messages.error(request, 'You do not have permission to access the admin interface.')
                    return redirect('jobs:dashboard')
            
        response = self.get_response(request)
        return response
