from django.shortcuts import redirect , render
from django.urls import reverse, resolve, Resolver404
from django.http import HttpResponseNotFound
from django.core.exceptions import PermissionDenied



# core/middleware.py (یا هر app دیگری)
import hashlib
from datetime import datetime

class NoCacheMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        
        # فقط برای صفحات HTML (نه static files)
        if not request.path.startswith('/static/') and not request.path.startswith('/media/'):
            
            # 🔥 Header های قوی‌تر برای جلوگیری از کش
            response['Cache-Control'] = 'no-store, no-cache, must-revalidate, private, max-age=0'
            response['Pragma'] = 'no-cache'
            response['Expires'] = '0'
            
            # 🔥 ETag یونیک برای هر response
            content = getattr(response, 'content', b'')
            if content:
                etag = hashlib.md5(str(datetime.now().timestamp()).encode()).hexdigest()
                response['ETag'] = f'"{etag}"'
            
            # 🔥 Vary برای force revalidate
            response['Vary'] = 'Cookie, Accept-Encoding'
            
            # 🔥 جلوگیری از Back/Forward cache
            response['X-Accel-Expires'] = '0'
        
        return response
        
        