import logging
from collections.abc import Callable
from functools import wraps
from typing import Concatenate

from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from django.http import HttpRequest, JsonResponse

logger = logging.getLogger(__name__)


def clear_previos_sessions(request: HttpRequest) -> None:
    sessions = Session.objects.order_by("-expire_date")
    if not isinstance(request.user, User):
        msg = "Пользователь не авторизован"
        raise TypeError(msg)
    for session in sessions:
        session_data_decoded = session.get_decoded()
        if "_auth_user_id" in session_data_decoded and int(session_data_decoded["_auth_user_id"]) == int(
            request.user.pk
        ):
            session.delete()


def ajax_login_required[**P, R](
    view_func: Callable[Concatenate[HttpRequest, P], R],
) -> Callable[Concatenate[HttpRequest, P], R | JsonResponse]:
    @wraps(view_func)
    def wrapper(request: HttpRequest, *args: P.args, **kwargs: P.kwargs) -> R | JsonResponse:
        if not request.user.is_authenticated:
            logger.warning("Попытка неавторизованного доступа: запрос отклонён.", request.user)
            return JsonResponse({"msg": "Unauthorized"}, status=401)
        return view_func(request, *args, **kwargs)

    return wrapper
