"use strict";

const express = require("express");
//const bodyHand = require("body");
const config = require("./config-handler");
// const http = require("http");
const { Database } = require("./database");
const { Logger } = require('./logger');
const bodyParser = require('body-parser');

const app = express();
// Выставляем адекватное ограничение на тело запроса
app.use(bodyParser.json({limit: config().request_size_limit}));

app.use(
	(req, res, next) => {
		if (req.query.response_format === 'json') {
			res.result = function (data, isErr = false, code = 200) {
				this.status(code).json(!isErr ? {
					response : data
				} : {
					error : data
				});
			};
		}
		next();
	}
);

app.use(async (req, res, next) => {
	req.logger = new Logger();
	req.logger.log(
		new Date(),
		req.ip,
		`Пользователь обратился по пути: ${req.originalUrl} (HTTP ${req.httpVersion}; ${req.method})`
	);
	next();
});

app.use("/", require("./page-view"));
app.use("/api", require("./api"));

// Подключение через HTTPS
let server;
if (!config().ssl.enabled) {
	server = app;
} else {
	const https = require("https");
	server = https.createServer(
		{
			cert: fs.readFileSync(config().ssl["public"], "utf-8"),
			key: fs.readFileSync(config().ssl["private"], "utf-8"),
		},
		app,
	);
}

server.listen(config().port, config().address, async (err) => {
	if (err) {
		throw err;
	} else {
		console.log(
			`Kodex Muzic catalog runned at ${config().address}:${config().port}`,
		);
	}
});
