import base64
from hashlib import sha384

from .models import CFAPIKeys


def hash_api_key(api_key: str) -> str:
    """Hash the API key using SHA-384 and encode the result using base64url.
    The hashing source of truth implementation is the hashApiKey function in js/common/token-functions.ts.

    Parameters
    ----------
    - api_key (str): The API key to hash.

    Returns
    -------
    - str: The base64url-encoded hash of the API key.

    """
    hashed_key = sha384(api_key.encode("utf-8")).digest()
    # Use urlsafe_b64encode for base64url encoding
    return base64.urlsafe_b64encode(hashed_key).decode("utf-8")


async def instance_for_api_key(hashed_api_key: str) -> CFAPIKeys | None:
    """Retrieve the CFAPIKeys instance associated with the given API key.

    Parameters
    ----------
    - api_key (str): The API key to look up.

    Returns
    -------
    - CFAPIKeys: The CFAPIKeys instance

    """
    try:
        return await CFAPIKeys.objects.aget(key=hashed_api_key)
    except CFAPIKeys.DoesNotExist:
        return None
