import _ from 'lodash';
import { requestApi, requestServiceApi } from 'lib/requestApi';
import ConfigStore from 'stores/Config';
import Url from 'lib/Url';

const api = {
    read,
    update,
    remove,
    create,
    createWithExternalUser,
    changeOwner,
    getOwnerChangeStatus,
    addDomain,
    changeMasterDomain,
    bindWithResource,
    getOrganizationsToBind,
};

_.set(window.ya.connect, 'api.org', api);

export default api;

function read(options) {
    return requestApi('GET', 'organization', { query: options });
}

function update(data) {
    return requestApi('PATCH', 'organization', { data });
}

function remove(data) {
    return requestApi('DELETE', 'organization', { data });
}

function create(data) {
    const params = {
        noOrgId: true,
        data: _.extend({
            language: ConfigStore.get('app.defaultLocale'),
            tld: ConfigStore.get('app.tld'),
            source: Url.getSourceParams() || 'unknown',
        }, data),
    };

    let outerId = Url.getQueryParam('outer_id');

    try {
        // бек ожидает что outer_id будет числом
        outerId = Number(outerId);
    } catch (e) {
        outerId = null;
    }

    if (outerId) {
        params.data.outer_id = outerId;
    }

    return requestApi('POST', 'organization', params);
}

function createWithExternalUser(data) {
    return requestApi('POST', 'organization/new', { data });
}

function changeOwner(data) {
    return requestApi('POST', 'org/change-owner', { data });
}

function getOwnerChangeStatus(data) {
    return requestServiceApi('GET', 'org/change-owner/status', { query: data });
}

function addDomain(data) {
    return requestApi('POST', 'organization/domain', {
        data: _.extend({
            language: ConfigStore.get('app.defaultLocale'),
            tld: ConfigStore.get('app.tld'),
            source: 'adminka',
        }, data),
    });
}

/**
 * Изменяем основной домен организации
 * @param {String} name
 * @returns {Promise}
 */
function changeMasterDomain(name) {
    const data = {
        master_domain: name,
    };

    return requestApi('PATCH', 'organization', { data });
}

function bindWithResource(data, query) {
    return requestApi('POST', 'organization/bind', { data, query });
}

function getOrganizationsToBind(data) {
    return requestApi('POST', 'organization/bind/organizations', { data });
}
