from rest_framework.authentication import BaseAuthentication
from integration.models import IntegrationTokens
from rest_framework.exceptions import AuthenticationFailed


class PublicAPIIntegrationAuthentication(BaseAuthentication):
    def authenticate(self, request):
        auth_header = request.headers.get("Authorization")

        if not auth_header or not auth_header.startswith("Bearer "):
            raise AuthenticationFailed(
                "No access token found. Request for a valid token."
            )

        try:
            access_token = auth_header.split(" ")[1]
            integrated_tokens = IntegrationTokens.objects.get(access_token=access_token)

            if integrated_tokens.is_access_token_expired:
                raise AuthenticationFailed("Access Token is expired.")

            request.client = integrated_tokens.client

            return (integrated_tokens.client, access_token)
        except IntegrationTokens.DoesNotExist:
            raise AuthenticationFailed(
                "Access Token is invalid. Request for a new one."
            )
