import APIClient from '@connect/api-client';
import { getCookie } from '@connect/cookies-lite';

const token = document.querySelector('meta[name="csrf_token"]').content;
const { state: { session: uid, organization: orgId }, requestId } = window.ya.connect.initial;
const debugId = new URL(window.location.href).searchParams.get('debug');

export function getHeaders({ body }) {
    const headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
        Pragma: 'no-cache',
        'x-csrf-token': token,
        'x-uid': uid,
        'x-org-id': orgId,
        'x-request-id': requestId,
        'x-client-version': window.ya.connect.config.app.version,
    };

    // @see DIR-1962
    if (debugId) {
        headers['x-debug'] = debugId;
    }

    // @see DIR-2533
    if (getCookie('connect_first_load')) {
        headers['x-first-visit'] = 'yes';
    }

    if (body instanceof FormData) {
        // убираем Content-Type, чтобы получать автоматически сгенерированный
        // заголовок для FormData с указанием boundary
        delete headers['Content-Type'];
    }

    return headers;
}

const directory = new APIClient(`/portal/apiproxy/org/${orgId}/directory`, opts => {
    return {
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'include',
        headers: getHeaders(opts),
    };
}, 1000);

const directoryWithoutOrg = new APIClient('/portal/apiproxy/directory', opts => {
    const headers = getHeaders(opts);

    delete headers['x-org-id'];

    return {
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'include',
        headers,
    };
}, 1000);

export { directory, directoryWithoutOrg };
export default window.ya.connect.directory = directory;
