import _ from 'lodash';
import { Promise } from 'rsvp';
import getErrors from 'lib/getErrors';
import AuthStore from 'stores/Auth';

import orgApi from 'api/org';
import domainApi from 'api/domain';
import userApi from 'api/user';

export default {
    submitDetails,
    submitInitialData,
    addDomain,
    createWithExternalUser,
    bindWithResource,
    getOrganizationsToBind,
};

function submitDetails(data) {
    const orgDetails = _.omit(data, ['domain', 'email']);
    const domain = data.domain;

    const userId = AuthStore.getUserId();
    let userData;

    if (data.email) {
        userData = {
            recovery_email: data.email,
        };
    }

    return Promise.all([
        !_.isEmpty(orgDetails) ? orgApi.update(orgDetails) : null,
        domain ? domainApi.add(domain) : null,
    ])
        .then(responses => {
            const errors = {
                org: getErrors(responses[0]),
                domain: getErrors(responses[1]),
            };

            errors.all = errors.org;

            if (errors.domain.get('_common')) {
                errors.all = errors.all.set('domain', errors.domain.get('_common'));
            }

            if (!errors.all.isEmpty()) {
                return { errors: errors.all };
            }

            if (userId && userData) {
                return userApi.update(userData, userId)
                    .then(response => {
                        errors.user = getErrors(response);

                        if (errors.user.get('_common')) {
                            errors.all = errors.all.set('email', errors.user.get('_common'));
                        }

                        if (!errors.all.isEmpty()) {
                            return { errors: errors.all };
                        }
                    });
            }
        });
}

function submitInitialData(data) {
    return orgApi.create(data);
}

function addDomain(data) {
    return orgApi.addDomain(data);
}

function createWithExternalUser(data) {
    return orgApi.createWithExternalUser(data)
        .then(response => {
            const errors = getErrors(response);

            if (!errors.isEmpty()) {
                return { errors };
            }

            return {
                orgId: _.get(response, 'added_organization.org_id'),
            };
        });
}

function bindWithResource(data, query) {
    return orgApi.bindWithResource(data, query)
        .then(response => {
            const errors = getErrors(response);

            if (!errors.isEmpty()) {
                return { errors, originalError: response };
            }

            return {
                orgId: _.get(response, 'bind_organization.org_id'),
            };
        });
}

function getOrganizationsToBind(data) {
    return orgApi.getOrganizationsToBind(data)
        .then(response => {
            const errors = getErrors(response);

            if (!errors.isEmpty()) {
                return { errors, originalError: response };
            }

            return {
                organizations: _.get(response, 'organizations_to_bind'),
            };
        });
}
