import merge from 'lodash/merge';
import APIClient from '@connect/api-client';
import { UserSettingsStore } from 'lib2/stores';

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

let apiClient = new APIClient('/portal/apiproxy/settings/connect', {
    mode: 'cors',
    cache: 'no-cache',
    credentials: 'include',
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
        Pragma: 'no-cache',
        'x-uid': uid,
        'x-csrf-token': token,
        'x-request-id': requestId,
        'x-client-version': window.ya.connect.config.app.version,
    },
});

export function saveSetting(key, value) {
    return apiClient.send('PUT', '', {
        body: JSON.stringify(merge(
            UserSettingsStore.getState(),
            { [key]: value }
        )),
    });
}

export function removeSetting(key) {
    let data = { ...UserSettingsStore.getState() };

    delete data[key];

    return apiClient.send('PUT', '', {
        body: JSON.stringify(data),
    });
}

window.ya.connect.saveSetting = saveSetting;
window.ya.connect.removeSetting = removeSetting;

export default apiClient;
