• Refreshes the access token using the stored refresh token

    Returns Promise<SpotifyTokenRefreshResponse>

    Promise resolving to token response with new access token

    Error if refresh fails or no refresh token is available

    export async function refreshAccessToken(): Promise<SpotifyTokenRefreshResponse> {
    ensureCredentialsSet();

    if (!refreshToken) {
    throw new Error("No refresh token available");
    }

    try {
    const { clientId, clientSecret } = getCredentials();
    const response = await axios.post(
    TOKEN_URL,
    querystring.stringify({
    grant_type: "refresh_token",
    refresh_token: refreshToken,
    client_id: clientId,
    client_secret: clientSecret,
    }),
    {
    headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    },
    },
    );

    const tokenResponse = response.data as SpotifyTokenRefreshResponse;
    const new_refresh_token = tokenResponse.refresh_token || refreshToken;

    // Update tokens
    setTokens(
    tokenResponse.access_token,
    new_refresh_token,
    tokenResponse.expires_in,
    );

    saveLog("Successfully refreshed access token", "DEBUG");
    return tokenResponse;
    } catch (error: unknown) {
    const err = error as Error;
    saveLog(`Failed to refresh access token: ${err.message}`, "ERROR");
    throw new Error(`Failed to refresh access token: ${err.message}`);
    }
    }