from django.conf import settings
from django.contrib.auth import logout
from django.shortcuts import redirect
from django.utils import timezone

SESSION_LAST_ACTIVITY = "skv_last_activity"
SESSION_TIMEOUT_SECONDS = int(getattr(settings, "SKEVER_SESSION_TIMEOUT_SECONDS", 120))

class SessionSecurityMiddleware:
    """Authoritative inactivity timeout for authenticated SKEVER staff sessions.

    A session expires after the configured period without a request. Business
    records/drafts are database objects and are never deleted by this middleware.
    """
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user.is_authenticated:
            now = timezone.now().timestamp()
            previous = request.session.get(SESSION_LAST_ACTIVITY)
            if previous is not None and now - float(previous) >= SESSION_TIMEOUT_SECONDS:
                logout(request)
                request.session.flush()
                return redirect(f"/login/?timeout=1")
            request.session[SESSION_LAST_ACTIVITY] = now
            request.session.modified = True

        return self.get_response(request)
