from django.db.models.functions import Now
from ninja.errors import HttpError
from ninja.security import HttpBearer

from authapp.auth_utils import hash_api_key, instance_for_api_key
from authapp.models import CFAPIKeys


class AuthBearer(HttpBearer):
    async def authenticate(self, request, token):
        hashed_token = hash_api_key(token)
        try:
            num_users = await CFAPIKeys.objects.filter(key=hashed_token).aupdate(last_used=Now())
            if num_users == 0:
                raise HttpError(403, "Invalid API key")
            if num_users == 1:
                api_key_instance = await instance_for_api_key(hashed_token)
                if not api_key_instance:
                    print(f"Instance not found for api key {token}. Returning 403")
                    raise HttpError(403, "Invalid API key")
                request.user = api_key_instance.user_id
                request.tier = api_key_instance.tier
                return token
            print("THIS SHOULD NOT HAPPEN! More than one users found in the db with the same api key!")
            raise HttpError(403, "Invalid API key")
        except CFAPIKeys.DoesNotExist:
            raise HttpError(403, "Invalid API key")
