'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var urlHelper = require('../utils/urlHelper.js');
var logger = require('../utils/logger.js');

const setupNestedRoute = () => {
    return (req, res, next) => {
        const locals = res.app.locals.dprPaths;
        if (locals) {
            // Initialise originals once
            if (!locals.original) {
                locals.original = { ...locals };
            }
            const base = req.baseUrl && req.baseUrl.length > 0 ? req.baseUrl : undefined;
            const { original } = locals;
            // CASE 1: no baseUrl so reset to originals
            if (!base) {
                locals.nestedBaseUrl = undefined;
                Object.assign(locals, original);
                return next();
            }
            // CASE 2: baseUrl is the SAME as last time so skip
            if (locals.nestedBaseUrl === base) {
                return next();
            }
            logger.default.info('Running nested-route middleware', JSON.stringify({
                routerBase: req.baseUrl,
                mountPoint: req.originalUrl,
            }, null, 2));
            // CASE 3: baseUrl is NEW so apply nested version
            locals.nestedBaseUrl = base;
            locals.bookmarkActionEndpoint = urlHelper.setNestedPath(original.bookmarkActionEndpoint, base);
            locals.downloadActionEndpoint = urlHelper.setNestedPath(original.downloadActionEndpoint, base);
            locals.productCollectionEndpoint = urlHelper.setNestedPath(original.productCollectionEndpoint, base);
            locals.bookmarkListPath = urlHelper.setNestedPath(original.bookmarkListPath, base);
            locals.requestedListPath = urlHelper.setNestedPath(original.requestedListPath, base);
            locals.recentlyViewedListPath = urlHelper.setNestedPath(original.recentlyViewedListPath, base);
            locals.reportsCatalogue = urlHelper.setNestedPath(original.reportsCatalogue, base);
            locals.userReportsList = urlHelper.setNestedPath(original.userReportsList, base);
            locals.dprHomepage = urlHelper.setNestedPath(original.dprHomepage, base);
            locals.requestReportPath = urlHelper.setNestedPath(original.requestReportPath, base);
            locals.viewReportPath = urlHelper.setNestedPath(original.viewReportPath, base);
        }
        return next();
    };
};

exports.default = setupNestedRoute;
exports.setupNestedRoute = setupNestedRoute;
//# sourceMappingURL=setUpNestedRoute.js.map
