"use strict";

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

const app = express();

global.database = new Database(
	config().database.address,
	config().database.port,
	config().database.username,
	config().database.password,
	config().database.database,
);

http.ServerResponse.prototype.errorModeOn = function () {
	this.isError = true;
};

http.ServerResponse.prototype.bindNext = function (next) {
	this.next = next;
};

http.ServerResponse.prototype.sendModed = function (sendData) {
	// Модифицируем res.send
	if (sendData !== undefined && config().logger_mode) {
		this.responseData = sendData;
		require("./logger")(this.req, this, this.next);
	}
	this.send(sendData);
};

app.use((req, res, next) => {
	res.bindNext(next);
	next();
});

app.use((req, res, next) => {
	// Для добавления оригинального тела запроса
	const body = bodyHand(
		req,
		res,
		{
			limit: 9999999999,
			cache: false,
			encoding: "base64",
		},
		(err, body) => {
			if (!err) {
				req.byteBody = Buffer.from(body, "base64");

				// Запись в req.json при json
				if (!!req.headers && req.headers["content-type"]?.includes("json")) {
					try {
						req.json = JSON.parse(req.byteBody.toString("utf8"));
					} catch (_e) {}
				}
			}
			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}`,
		);
	}
});
