export let token = null;
export function setToken(value) {
    token = value;
}
export let prefix = '/api/';
export function setPrefix(value) {
    prefix = value;
}
export async function fetchAPI(method, endpoint, data, ...params) {
    const options = {
        method,
        headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json',
        },
    };
    if (method !== 'GET' && method !== 'HEAD')
        options.body = JSON.stringify(data);
    const search = method != 'GET' || typeof data != 'object' || data == null || !Object.keys(data).length
        ? ''
        : '?' + new URLSearchParams(data).toString();
    if (token)
        options.headers.Authorization = 'Bearer ' + token;
    const parts = [];
    for (const part of endpoint.split('/')) {
        if (!part.startsWith(':')) {
            parts.push(part);
            continue;
        }
        const value = params.shift();
        if (!value)
            throw new Error(`Missing parameter "${part.slice(1)}"`);
        parts.push(value);
    }
    const response = await fetch(prefix + parts.join('/') + search, options);
    if (!response.headers.get('Content-Type')?.includes('application/json')) {
        throw new Error(`Unexpected response type: ${response.headers.get('Content-Type')}`);
    }
    const json = await response.json().catch(() => ({ message: 'Unknown server error (invalid JSON response)' }));
    if (!response.ok)
        throw new Error(json.message);
    return json;
}
