const settings = require('../api2/settings');

const FallbackSettings = {
    initial_user_agreement: '0', // непустая строка - соглашение принято
    dashboard_intro_visited: true,
    admin_intro_visited: true,
    staff_intro_visited: true,
    news_mail_subscription: {
        confirm: true,
    },
    default: true,
};

const DefaultSubscriptionSettings = {
    confirm: false,
    last_shown: null,
    declined: false,
};

module.exports = () => (req, res, next) => {
    settings(req)
        .send('GET', '/connect')
        .then(res => res.ok ? res.json() : FallbackSettings)
        .then((data = {}) => {
            if (!data.news_mail_subscription) {
                data.news_mail_subscription = {
                    ...DefaultSubscriptionSettings,
                };
            }

            req.ctx.userSettings = data;

            next();
        })
        .catch(() => {
            req.ctx.userSettings = FallbackSettings;

            next();
        });
};
