'use strict';
if (process.env.QLOUD_ENVIRONMENT) {
    process.env.NODE_ENV = process.env.QLOUD_ENVIRONMENT;
}

const express = require('express');
const path = require('path');
const fs = require('fs');
const configs = require('./configs');

const logger = require('pino')(configs.logger);
const app = express();

if (isNaN(configs.port) && fs.existsSync(configs.port)) {
    fs.unlinkSync(configs.port);
}

process.on('uncaughtException', function(error) {
    logger.error(error.message, error);
});

app.use(require('./modules/middlewares/uid')(4));
app.use(require('express-pino-logger')({
    logger: logger,
    serializers: {
        req: require('./modules/logger/req_serializer')
    }
}));

app.use('/_', express.static(path.join(__dirname, '/bundles')));

app.get(
    '/favicon-:size.png',
    require('./modules/middlewares/favicon')(configs.env)
);

app.get('/ping', function(req, res) {
    res.sendStatus(200);
});

app.use(function(req, res, next) {
    req.configs = configs;

    next();
});

require('./modules/template')(app, logger);

app.set('view engine', 'bemhtml.js');
app.set('views', path.join(__dirname, 'bundles/'));

app.enable('trust proxy');
app.disable('etag');
app.disable('x-powered-by');

app.use(require('cookie-parser')());
app.use(require('express-yandex-csp')(configs.csp)),
app.use(require('express-blackbox')(configs.blackbox));
app.use(require('./modules/middlewares/checkauth')(configs));
app.use(require('body-parser').json());
app.use(require('body-parser').urlencoded({
    extended: true,
    limit: '10mb'
}));

require('./modules/routes')(app);

app.listen(configs.port, function() {
    logger.info(`Listening ${configs.port}`);

    if (isNaN(configs.port)) {
        fs.chmodSync(configs.port, '0777');
    }
});

logger.info(`App ${configs.name} version ${configs.version} started on ${process.pid}`);
