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 staff sessions.

    Business records and drafts are database objects and are never deleted
    when a session expires.
    """

    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:
                try:
                    elapsed = now - float(previous)
                except (TypeError, ValueError):
                    elapsed = 0

                if elapsed >= SESSION_TIMEOUT_SECONDS:
                    logout(request)
                    request.session.flush()
                    return redirect("/login/?timeout=1")

            request.session[SESSION_LAST_ACTIVITY] = now
            request.session.modified = True

        return self.get_response(request)
