from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from apps.apps_.models import APIKey

class APIKeyAuthentication(BaseAuthentication):
    keyword = "Api-Key"

    def authenticate(self, request):
        auth = request.headers.get("Authorization")
        if not auth or not auth.startswith(self.keyword):
            return None

        key = auth.split(" ")[1]
        try:
            api_key = APIKey.objects.get(key=key, revoked=False)
        except APIKey.DoesNotExist:
            raise AuthenticationFailed("Invalid API Key")

        return (api_key.app.company, None)
