const _ = require('lodash');
const responseContext = require('../../lib/responseContext');
const sendHandledRequest = require('../../lib/sendHandledRequest');

function check(req, res, next) {
    const { code } = req.query;

    return sendHandledRequest({
        method: 'get',
        url: [req.config.api.directory, 'invites', { value: code, type: 'code' }],
        source: req,
        label: 'check_invite_code',
    })
        .then(response => {
            req.context.invites = {
                [code]: _.extend({}, response, { valid: true }),
            };

            return next ? next() : req;
        })
        .catch(error => {
            const responseData = _.get(error, 'body');

            req.context.invites = {
                [code]: _.extend({}, responseData, { valid: false }),
            };

            return next ? next() : req;
        });
}
function createUser(req, res, next) {
    const { code, uid } = req.body;

    if (!responseContext.hasSession(req, uid)) {
        return res.sendStatus(403);
    }

    const headers = _.extend({}, _.omit(req.context.headers, ['x-org-id']), { 'x-uid': uid });

    return sendHandledRequest({
        method: 'post',
        url: [req.config.api.directory, 'v9', 'invites', { value: code, type: 'code' }, 'use'],
        headers,
        source: req,
        label: 'create_user_by_invite',
    })
        .then(response => {
            req.context.invited_user_data = response;

            return next ? next() : req;
        })
        .catch(next);
}

function inviteByEmails(req, res, next) {
    return sendHandledRequest({
        method: 'post',
        url: [req.config.api.directory, 'invites', 'emails'],
        source: req,
        label: 'invite_users_by_email',
    })
        .then(() => next ? next() : req)
        .catch(next);
}

module.exports = {
    check,
    createUser,
    inviteByEmails,
};
