const express = require('express');
const {json} = require("body-parser");
const cors = require('cors');

const app = express();
const port = process.env.PORT || 5000;

app.use(cors({
    origin: '*', // Allow all origins
    methods: 'GET,POST,PUT,DELETE,PATCH', // Allow all methods
    allowedHeaders: '*', // Allow all headers
    credentials: true, // Enable credentials
    preflightContinue: false,
    optionsSuccessStatus: 204 // Some legacy browsers (IE11, various SmartTVs) choke on 204
}));
app.use(json());

const {apiKey} = require('./config.json');
app.locals.apiKey = apiKey;

const {
    usersDB,
    departmentsDB,
    backupSchemesDB,
    ceoDB,
    adminDB
} = require('./db/jsonDatabaseManager');

app.set('usersDB', usersDB);
app.set('departmentsDB', departmentsDB);
app.set('backupSchemesDB', backupSchemesDB);
app.set('ceoDB', ceoDB);
app.set('adminDB', adminDB);

app.use('/heartbeat', (req, res) => {
    return res.status(200).json({message: 'Server ap and running.'});
})

const checkJson = require('./middlewares/checkJson');
const apiKeyValidation = require('./middlewares/apiKeyValidation');

app.use(apiKeyValidation)
app.use(checkJson)

const usersRouter = require('./routes/users');
const adminRouter = require('./routes/admin');
const ceoRouter = require('./routes/ceo');
const backupSchemesRouter = require('./routes/backup_schemes');

app.use('/users', usersRouter);
app.use('/admin', adminRouter);
app.use('/ceo', ceoRouter);
app.use('/backup_schemes', backupSchemesRouter);

app.use('/heartbeat', (req, res) => {
    return res.status(200).json({message: 'Server ap and running.'});
})

app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`);
});

// Graceful shutdown function
function gracefulShutdown() {
    console.log('\nShutting down!');
    process.exit(0);
}

process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);