import { getBasePath } from 'talon/configProvider';
import { getCSRFToken } from 'talon/sessionService';
import { assert } from 'talon/utils';
import { API_PATH_PREFIX } from '@webruntime/common';

const methodsWithCSRF = ['POST', 'PATCH', 'PUT', 'DELETE'];

/**
 * Makes a request using the fetch API with the given path, method and body.
 *
 * This method takes care of setting the credentials to 'same-origin'
 * and adds the Content-Type header if a body is passed.
 *
 * @param {String} path - The request path, should be absolute but we prepend /<basePath>/api to it
 * @param {Object} init - An options object containing any custom settings that you want to apply to the request.
 * @param {String} init.credentials - The request credentials you want to use for the request, same-origin unless specified
 */
export async function fetch(path, init = {}) {
    assert(path, 'Path not provided for API request');

    const url = `${getBasePath()}${API_PATH_PREFIX}${path}`;

    const initParams = {
        ...init,
        headers: { ...init.headers },
        credentials: init.credentials || 'same-origin',
    };

    initParams.headers['Content-Type'] =
        initParams.headers['Content-Type'] || (init.body && 'application/json; charset=utf-8');

    addCSRFToken(initParams);

    return self.fetch(url, initParams);
}

function addCSRFToken(params) {
    if (params.method && methodsWithCSRF.includes(params.method)) {
        const csrfToken = getCSRFToken();
        if (csrfToken) {
            params.headers['CSRF-Token'] = csrfToken;
        }
    }
}
