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"


def _timeout_seconds():
    return int(getattr(settings, "SKEVER_SESSION_TIMEOUT_SECONDS", 120))


class SessionSecurityMiddleware:
    """
    Server-authoritative inactivity timeout for authenticated SKEVER staff.

    The session is ended after the configured period of inactivity.
    Business records and 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:
                try:
                    elapsed = now - float(previous)
                except (TypeError, ValueError):
                    elapsed = 0

                if elapsed >= _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)
