import logging

from asgiref.sync import iscoroutinefunction, markcoroutinefunction
from django.conf import settings
from django.http import JsonResponse
from django.utils.decorators import async_only_middleware
from ninja.errors import HttpError

from authapp.auth import AuthBearer


@async_only_middleware
class AuthMiddleware:
    def __init__(self, get_response) -> None:
        self.get_response = get_response
        self.auth_bearer = AuthBearer()

        # Check if the `get_response` function is a coroutine (async)
        if iscoroutinefunction(self.get_response):
            logging.debug("AuthMiddleware is async.")
            # Mark this middleware as async if get_response is async
            markcoroutinefunction(self)  # type: ignore[arg-type]

    async def __call__(self, request):
        token = request.headers.get("Authorization")  # Extract the token from the Authorization header

        if not token:
            return JsonResponse({"error": "Invalid API key"}, status=403)

        # Authenticate the token - only catch auth-related exceptions here
        try:
            # Strip "Bearer " prefix if present
            token = token.replace("Bearer ", "")
            await self.auth_bearer.authenticate(request, token)
        except HttpError as e:
            # HttpError from auth layer - invalid API key
            return JsonResponse({"error": e.message}, status=e.status_code)
        except Exception as e:
            response_error = str(e) if settings.DEBUG else "Authentication failed"
            return JsonResponse({"error": response_error}, status=500)

        # Process the request - let downstream exceptions propagate naturally
        # so they get proper error handling by Django/Ninja
        return await self.get_response(request)
