/**
 * Незалогиновая ручка для проверки можно ли завести новую организацию
 */

const { URL } = require('url');
const _ = require('lodash');
const logger = require('../lib/logger');
const template = require('../lib/template');
const responseContext = require('../lib/responseContext');
const services = require('../routes/api/services');

/**
 * Редиректит на указанный урл и логирует переход
 * @param {Request} req
 * @param {Response} res
 * @param {Object} params
 * @param {String} params.url
 * @param {String} params.message
 */
function redirect(req, res, { url, message }) {
    logger.info(`Register: ${message}`, req, {
        url,
    });

    res.redirect(url);
}

function redirectToRegistration(req, res) {
    const { config } = req;
    const currentUrl = responseContext.getUrl(req, req.originalUrl);
    const { origin: serviceName } = req.query;

    const parsedQuery = new URL(currentUrl).searchParams;

    let retpath = parsedQuery.get('retpath');

    parsedQuery.append('session', 'current');

    if (serviceName && !retpath) {
        retpath = responseContext.getUrl(req, `portal/services/${serviceName}`);
        parsedQuery.append('retpath', encodeURIComponent(retpath));
    }

    redirect(req, res, {
        message: 'Redirect to registration',
        url: template.build(_.get(config, 'org.registration.yo'), {
            host: responseContext.getHost(req),
            query: `?${parsedQuery.toString()}`,
        }),
    });
}

module.exports = function(req, res) {
    const serviceSlug = req.query.origin;
    // в предшествующей миддлваре organizations в заголовок x-org-id
    // проставлен id текущей организации из Y-куки и её фолбэков
    const orgId = responseContext.isFeatureEnabled('multiorg') ?
        req.context.headers['x-org-id'] :
        responseContext.getOrgIdFromSession(req);

    if (!serviceSlug || !orgId || !responseContext.isInternal(req)) {
        return redirectToRegistration(req, res);
    }

    return services.readAll(req)
        .then(() => {
            const isServiceEnabled = responseContext.isServiceEnabled(req, serviceSlug);
            const serviceUrl = responseContext.getServiceUrl(req, serviceSlug);

            if (!serviceUrl) {
                throw new Error('Service Url is not defined');
            }

            if (!isServiceEnabled) {
                return redirectToRegistration(req, res);
            }

            return redirect(req, res, {
                message: `Redirect to ${serviceSlug}`,
                url: serviceUrl,
            });
        })
        .catch(() => redirectToRegistration(req, res));
};
