from django.utils.deprecation import MiddlewareMixin
from django.core.cache import cache


class NoCacheAuthenticatedMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        try:
            path = request.path or ''
            user = getattr(request, 'user', None)
            is_authed = bool(user and getattr(user, 'is_authenticated', False))
            sensitive_paths = (
                path.startswith('/staff/')
                or path.startswith('/profile/')
                or path.startswith('/orders/')
                or path.startswith('/vendor/')
            )
            if is_authed or sensitive_paths:
                response['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
                response['Pragma'] = 'no-cache'
                response['Expires'] = '0'
        except Exception:
            pass
        return response


class SecurityHeadersMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        try:
            csp = "default-src 'self'; img-src 'self' data: blob: https:; style-src 'self' 'unsafe-inline' https:; script-src 'self' 'unsafe-inline' https:; font-src 'self' https: data:; frame-ancestors 'self'; object-src 'none'; base-uri 'self'"
            response['Content-Security-Policy'] = csp
            response['Referrer-Policy'] = 'strict-origin-when-cross-origin'
            response['X-Content-Type-Options'] = 'nosniff'
            response['X-Frame-Options'] = 'DENY'
            response['Permissions-Policy'] = 'geolocation=(), microphone=(), camera=(), fullscreen=(self)'
        except Exception:
            pass
        return response


class RateLimitMiddleware(MiddlewareMixin):
    def process_request(self, request):
        try:
            path = request.path or ''
            ip = request.META.get('REMOTE_ADDR') or 'unknown'
            key = f"rl:{ip}:{path}"
            limit = 60
            if path.startswith('/api/payments/bank/'):
                limit = 10
            elif path.startswith('/accounts/login') or path.startswith('/login'):
                limit = 50
            count = cache.get(key, 0)
            if count >= limit:
                if path.startswith('/api/') or request.headers.get('Accept') == 'application/json':
                    from django.http import JsonResponse
                    return JsonResponse({'success': False, 'message': 'Rate limit exceeded'}, status=429)
                else:
                    from django.http import HttpResponse
                    html = """
                    <html>
                    <head><title>Too Many Requests</title></head>
                    <body style="font-family: sans-serif; text-align: center; padding: 50px;">
                        <h1>Too Many Requests</h1>
                        <p>You have exceeded the rate limit. Please try again in a minute.</p>
                    </body>
                    </html>
                    """
                    return HttpResponse(html, status=429)
            cache.set(key, count + 1, 60)
        except Exception:
            pass
        return None
