import APIClient from '@connect/api-client';

const token = document.querySelector('meta[name="csrf_token"]').content;
const { state: { session: uid, organization: orgId }, requestId } = window.ya.connect.initial;

export default new APIClient(`/portal/apiproxy/org/${orgId}/directory`, {
    mode: 'cors',
    cache: 'no-cache',
    credentials: 'include',
    headers: {
        'x-encoding': 'binary',
        '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,
    },
}, 1000).resolve((req, res) => {
    let { ok, status, statusText } = res;

    if (!ok) {
        return res.text().then(body => {
            try {
                body = JSON.parse(body);
            } catch (e) {
                // noop
            }

            return { ok, status, statusText, body };
        });
    }

    return res.blob().then(body => ({ ok, status, statusText, body }));
});
