const getList = require('../util/org/getList');
const addListDetails = require('../util/org/addListDetails');
const getStats = require('../util/org/getStats');
const preprocessOrganizationList = require('../util/org/preprocessList');
const layout = require('../util/layout');

module.exports = (req, res, next) => {
    const listMode = Boolean(req.query.query) || /^\/recent(\/|$)/.test(req.path);

    if (!listMode) {
        return layout(req, res).render('org_search');
    }

    return Promise
        .all([
            getList(req, res),
            getStats(req, res),
        ])
        .then(([list, stats]) => {
            // если нашлась только одна организация,
            // сразу открываем информацию о ней
            if (list.result && list.result.length === 1) {
                return res.redirect(`/organizations/${list.result[0].id}`);
            }

            return addListDetails(req, res, list) // DIR-3245
                .then(extendedList => {
                    let titleId;

                    if (req.query.query)
                        titleId = 'search_results';
                    else if (req.params.plan === 'paid')
                        titleId = 'paid_orgs';

                    layout(req, res).render('org_list', {
                        title_id: titleId,
                        org_list: preprocessOrganizationList(req, res, extendedList),
                        stats,
                    });
                });
        })
        .catch(next);
};
