from django.utils import timezone
from rest_framework import authentication, exceptions

from .models import APIKey


class APIKeyAuthentication(authentication.BaseAuthentication):
    keyword = "Bearer"

    def authenticate(self, request):
        header = request.headers.get("Authorization", "")

        parts = header.split()

        if len(parts) != 2 or parts[0].lower() != self.keyword.lower():
            raise exceptions.AuthenticationFailed(
                "Missing or invalid API key."
            )

        raw_key = parts[1]

        api_key = APIKey.objects.filter(
            key_hash=APIKey.hash_key(raw_key),
            is_active=True,
        ).first()

        if api_key is None:
            raise exceptions.AuthenticationFailed(
                "Missing or invalid API key."
            )

        APIKey.objects.filter(pk=api_key.pk).update(
            last_used_at=timezone.now()
        )

        return api_key, api_key