// Use required packages and get configs
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const yaml = require('yamljs'); // Parse YAML
const swaggerUi = require('swagger-ui-express'); // Swagger UI

// Load YAML API definition
const swaggerDocument = yaml.load(path.join(__dirname, 'api_definition.yaml'));

// Load routes
const usersRouter = require('./routes/users'); // users.js
const instructorsRouter = require('./routes/instructors'); // instructors.js
const studentsRouter = require('./routes/students'); // students.js
const tasRouter = require('./routes/tas'); // tas.js
const teamsRouter = require('./routes/teams'); // teams.js
const suppliersRouter = require('./routes/suppliers'); // suppliers.js
const partsRouter = require('./routes/parts'); // parts.js
const requestsRouter = require('./routes/requests'); // requests.js
const ordersRouter = require('./routes/orders'); // orders.js
const notificationsRouter = require('./routes/notifications');
const readNotificationsRouter = require('./routes/read_notifications');
const clearDataRouter = require('./routes/clear_data');

// Serve app on port 3000
const app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// Middleware to check Referer header
const validateReferer = (req, res, next) => {
    const allowedReferers = [
        'https://' + process.env.VITE_APP_URL,
        'http://localhost', // for development
    ];

    const referer = req.headers.referer;

    if (!req.headers.host.includes('localhost')) {
        // Block requests without a valid Referer/Origin
        if (
            !referer ||
            !allowedReferers.some((allowed) => referer.startsWith(allowed))
        ) {
            return res
                .status(403)
                .json({ error: 'Forbidden: Invalid request source.' });
        }
    }

    next();
};

// Apply the middleware to all API routes
app.use(validateReferer);

// Serve routes
const apiLocation = '/api';
app.use(apiLocation, usersRouter); // users.js
app.use(apiLocation, instructorsRouter); // instructors.js
app.use(apiLocation, studentsRouter); // students.js
app.use(apiLocation, tasRouter); // tas.js
app.use(apiLocation, teamsRouter); // teams.js
app.use(apiLocation, suppliersRouter); // suppliers.js
app.use(apiLocation, partsRouter); // parts.js
app.use(apiLocation, requestsRouter); // requests.js
app.use(apiLocation, ordersRouter); // orders.js
app.use(apiLocation, notificationsRouter);
app.use(apiLocation, readNotificationsRouter);
app.use(apiLocation, clearDataRouter);
app.use('/', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); // Swagger UI

module.exports = app;
