import _ from 'lodash';
import { ActionTypes } from 'constants/Common';
import getErrors from 'lib/getErrors';
import inviteApi from 'api/invite';

import dispatcher from 'dispatcher';

export default {
    createUser,
    inviteByEmails,
    createInviteLink,
    readInviteLink,
    removeInviteLink,
};

function createUser(data) {
    return inviteApi.createUser(data).then(response => {
        const errors = getErrors(response);

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

        return _.get(response, 'invited_user_data');
    });
}

/**
 * Приглашение новых пользователей по email
 * @method  inviteByEmails
 * @param   {Object} data
 * @returns {Promise}
 */
function inviteByEmails(data) {
    return inviteApi.inviteByEmails(data).then(response => {
        const errors = getErrors(response);

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

        return response;
    });
}

/**
 * Создание инвайт-ссылки
 * @method  createInviteLink
 * @param   {Object} data
 * @returns {Promise}
 */
function createInviteLink(data) {
    return inviteApi.createInviteLink(data).then(response => {
        const errors = getErrors(response);

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

        dispatcher.dispatch(ActionTypes.RECEIVE_INVITE_LINK, {
            invites: response.invites,
            departmentId: data.departmentId,
        });

        return response;
    });
}

/**
 * Чтение инвайт-ссылки
 * @method  readInviteLink
 * @param   {Object} data
 * @returns {Promise}
 */
function readInviteLink(data) {
    return inviteApi.readInviteLink(data).then(response => {
        const errors = getErrors(response);

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

        dispatcher.dispatch(ActionTypes.RECEIVE_INVITE_LINK, {
            invites: response.invites,
            departmentId: data.departmentId,
        });

        return response;
    });
}

/**
 * Удаление инвайт-ссылки
 * @method  removeInviteLink
 * @param   {Object} data
 * @returns {Promise}
 */
function removeInviteLink(data) {
    return inviteApi.removeInviteLink(data).then(response => {
        const errors = getErrors(response);

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

        dispatcher.dispatch(ActionTypes.DISCARD_INVITE_LINK, {
            departmentId: data.departmentId,
        });

        return response;
    });
}
