/**
 * Проверки/редиректы связанные с авторизацией
 */

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

const handleApiErrors = require('./handleApiErrors');

module.exports = (req, res, next) => {
    const currentUrl = `https://${responseContext.getHost(req)}${req.originalUrl}`;
    let nextUrl;

    const isAuthorized = responseContext.isAuthorized(req);
    const resetRequired = responseContext.isResetRequired(req);

    const requestType = req.accepts(['html', 'json']);
    const authData = _.get(req, 'context.auth', {});

    if (!isAuthorized) {
        if (requestType === 'json') {
            handleApiErrors(authData, req, res, next);

            return;
        }
        nextUrl = template.build(_.get(req.config, 'passport.session.login'), {
            retpath: encodeURIComponent(currentUrl),
        });

        logger.info(`Redirect to '${nextUrl}', unauthenticated`, req, req.context);
        res.redirect(nextUrl);

        return;
    }

    if (resetRequired && requestType === 'html') {
        nextUrl = template.build(_.get(req.config, 'passport.session.update'), {
            retpath: encodeURIComponent(currentUrl),
        });

        logger.info(`Redirect to '${nextUrl}' to update session for {uid:${authData['x-uid']}}`, req, req.context);
        res.redirect(nextUrl);

        return;
    }

    next();
};
