import express from 'express';
import cors from 'cors';
import cookieParser from 'cookie-parser';

import os from 'os';
import { indexRoutes } from './routes/indexRoutes';
import EnvVariableHelper from './utils/envVariableHelper';
import SecurityUtil from './utils/security/securityUtil';

const app = express();

app.disable('x-powered-by'); // replace with package ...

const corsOptions = {
    origin: [
        `${EnvVariableHelper.VARIABLES.FRONTEND_PROTOCOL}://${EnvVariableHelper.VARIABLES.FRONTEND_HOST}`,
        `${EnvVariableHelper.VARIABLES.FRONTEND_PROTOCOL}://www.${EnvVariableHelper.VARIABLES.FRONTEND_HOST}`,
    ],
    methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
    credentials: true,
    maxAge: 600,
    allowedHeaders: ['Content-Type', 'Accept', 'Authorization', 'Origin'],
    optionsSuccessStatus: 204,
};
app.use(cors(corsOptions));

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.use(cookieParser());
const hostname = os.hostname();

app.get('/', (req, res) => {
    res.redirect(
        `${EnvVariableHelper.VARIABLES.FRONTEND_PROTOCOL}://${EnvVariableHelper.VARIABLES.FRONTEND_HOST}:${EnvVariableHelper.VARIABLES.FRONTEND_PORT}`
    );
});

app.get('/hostname', (req, res) => {
    res.send(hostname);
});

app.use(SecurityUtil.sanitizeXssMiddleware());

app.use(indexRoutes);

const server = app.listen(EnvVariableHelper.VARIABLES.BACKEND_PORT, () => {
    console.log(
        `Server listening at http://${EnvVariableHelper.VARIABLES.BACKEND_HOST}:${EnvVariableHelper.VARIABLES.BACKEND_PORT}`
    );
});

// server.on('connection', function(socket) {
//     console.log("A new connection was made by a client.");
//     socket.setTimeout(1 * 1000);
//     // 30 second timeout. Change this as you see fit.
// });
// -> set keepAliveTimeout false
server.keepAliveTimeout = 30000; // for real loadbalancing of traefik
