"""JWT token helpers shared across the project."""

from datetime import datetime, timezone

TOKEN_TYPE = "Bearer"
TOKEN_DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"


def format_token_expiry(token) -> str:
    """Format a SimpleJWT token's `exp` claim as a UTC datetime string.

    Returns an empty string if the claim is missing.
    """
    exp = token.get("exp") if hasattr(token, "get") else None
    if exp is None:
        return ""
    return datetime.fromtimestamp(exp, tz=timezone.utc).strftime(TOKEN_DATETIME_FORMAT)


def jwt_envelope(access, refresh) -> dict:
    """Return a normalized dict describing a JWT pair.

    Used by login / refresh endpoints to keep the response shape consistent.
    """
    return {
        "access_token": str(access),
        "refresh_token": str(refresh),
        "token_type": TOKEN_TYPE,
        "expires_at": format_token_expiry(access),
        "refresh_expires_at": format_token_expiry(refresh),
    }
