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

/**
 * Добавление подтвержденной почты в список рассылок
 * @param {Request} req
 * @param {Response} res
 * @param {Function} next
 * @returns {Promise}
 */
function subscribe(req, res, next) {
    const { service, listId } = req.config.sender[req.body.mail_list];

    if (!responseContext.hasSessionWithEmail(req, req.body.email)) {
        return res.sendStatus(403);
    }

    return sendHandledRequest({
        method: 'put',
        url: [req.config.api.sender, 'api', '0', service, 'maillist', listId, 'subscription'],
        options: {
            formData: {
                email: req.body.email,
            },
            auth: {
                user: req.config.tokens.sender,
                pass: '',
            },
        },
        noTrailingSlash: true,
        source: req,
        label: 'subscribe_user',
    })
        .then(() => next ? next() : req)
        .catch(next);
}

/**
 * Отправка письма пользователю (на указанную им почту) для подписки по схеме double opt-in
 * @param {Request} req
 * @param {Response} res
 * @param {Function} next
 * @returns {Promise}
 */
function request(req, res, next) {
    const { service, listId } = req.config.sender[req.body.mail_list];

    return sendHandledRequest({
        method: 'post',
        url: [req.config.api.sender, 'api', '0', service, 'maillist', listId, 'subscription', 'request'],
        options: {
            formData: {
                to_email: req.body.to_email,
                args: JSON.stringify(req.body.args),
            },
            auth: {
                user: req.config.tokens.sender,
                pass: '',
            },
        },
        noTrailingSlash: true,
        source: req,
        label: 'request_user_email',
    })
        .then(() => next ? next() : req)
        .catch(next);
}

module.exports = { subscribe, request };
