import { API_HOST } from './config';

export async function initToken(): Promise<unknown> {
    const response = await fetch(`${API_HOST}/api/guest/init_cookie?utm_source=hvatilo_promo`, {
        method: 'POST',
        credentials: 'include',
    });

    return response.json();
}

export async function refreshToken(): Promise<unknown> {
    const response = await fetch(`${API_HOST}/api/guest/refresh_cookie`, {
        method: 'POST',
        credentials: 'include',
    });

    if (response.status === 400) {
        await fetch(`${API_HOST}/api/guest/clear_cookie`, {
            method: 'POST',
            credentials: 'include',
        });

        await new Promise(resolve => setTimeout(resolve, 100));

        return initToken();
    }

    return response.json();
}