const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const hbs = require('hbs');
const redirect = require('./middleware2/redirect');

require('./lib2/dnsLookupPatch');
require('./lib2/consolePatch');

app.enable('trust proxy');
app.disable('x-powered-by');
app.set('view engine', 'hbs');
app.set('views', './server/views');
app.use(require('cookie-parser')());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(require('./middleware2/init')());
app.use(require('./middleware2/deprecatedHost')());

hbs.registerPartials(path.join(__dirname, 'views'));

if (process.env.HOT_RELOAD) {
    app.use(require('./middleware2/webpackHotReload')());
}
if (process.env.LOCAL_STATIC) {
    app.use('/portal', express.static(path.join(__dirname, '../build'), { redirect: false }));
}
if (!process.env.CSRF_PROTECTION_DISABLED) {
    app.use(require('csurf')({ cookie: true }));
}

// app.get('/', require('./routes2/devRoot')());
app.get('/pdd(_old)?', redirect('https://pdd.yandex.${tld}'));
app.get('/widget/:widgetId', redirect('/portal/widget/${widgetId}'));
app.get('/:section(registration|register|onboarding|start|home|invites|forbidden|error)',
    redirect('/portal/${section}'));
app.get('/portal/users/:userId', redirect('/portal/admin/users/${userId}')); // Стафф-лайт
app.get('/ping', require('./routes2/healthCheck')());
app.get('/portal/ping', require('./routes2/healthCheck')());
app.use('/portal/favicon.ico', express.static(path.join(__dirname, '../static/favicon.ico')));

// redirects from deprecated pages
app.get('/portal/admin/profile', redirect('/portal/profile'));
app.get('/portal/admin/subscription/services', redirect('/portal/home'));
app.get('/portal/admin/subscription/manage', redirect('/portal/services/tracker'));
app.get('/portal/admin/subscription', redirect('/portal/services/tracker'));
app.get('/portal/onboarding/yo', redirect('/portal/start'));

app.get('/suggest', require('./routes2/suggestLocalProxy')());
app.use('/portal/apiproxy', require('./routes2/apiProxy')());
app.use('/portal/serviceapi', require('./routes2/legacyServiceApi')());
app.use('/portal/api', require('./routes2/legacyApi')());
app.use('/portal/auth', require('./routes2/legacyDevAuthProxy')());

app.get([
    '/portal/services/:serviceSlug',
    '/portal/services/:serviceSlug/*',
], require('./routes2/services')());

app.get('/portal/profile', require('./routes2/profile')());
app.get([
    '/portal/balance',
    '/portal/balance/contract',
], require('./routes2/balance')());

app.get('/portal/home', require('./routes2/home')());
app.get('/portal/start', require('./routes2/onboarding')());
app.get('/portal/invites', require('./routes2/invites')());

app.get('/portal/registration', require('./routes2/registration')());
app.get('/portal/:section(register|join)', require('./routes2/register')());
app.get('/portal/context', require('./routes2/context')());

app.get('/portal/widget/add-resource', require('./routes2/bind')());
app.get('/portal/widget/bind-fake-page', require('./routes2/fakeBind')());
app.get('/portal/widget/bind-promo', require('./routes2/bindPromo')());

app.get('/portal/error', require('./routes2/error')());
app.get('/portal/forbidden', require('./routes2/forbidden')());

app.get('*', require('./routes2/index')());
app.use(require('./middleware2/error')());

if (require.main === module) {
    let config = require('./config');

    app.listen(config.server.port, function() {
        // eslint-disable-next-line no-console
        console.log(`Listening ${JSON.stringify(this.address())}`);

        if (process.env.HOT_RELOAD) {
            // eslint-disable-next-line no-console
            console.log('Waiting for webpack...');
        }
    });
} else {
    module.exports = app;
}
