import { API_HOST } from './config';
import { refreshToken } from './tokenApi';

export function apiUrl(path: string): string {
    return `${API_HOST}${path}`;
}

export async function requestWithRefresh<TResponse>(
    url: string,
    options: RequestInit = {},
): Promise<TResponse> {
    const response = await fetch(url, {
        ...options,
        credentials: 'include',
    });

    const data = await response.json();

    if (data?.error_message === 'need_refresh') {
        await refreshToken();

        const retryResponse = await fetch(url, {
            ...options,
            credentials: 'include',
        });

        return await retryResponse.json() as Promise<TResponse>;
    }

    return Promise.resolve(data) as Promise<TResponse>;
}