const express = require("express");
const router = express.Router();
const fs = require("fs");
const config = require('../../config-handler');
const database = require('../../database');
const bodyParser = require('body-parser');

// Парсинг куки
//router.use(require('cookie-parser')());

// Парсим JSON
router.use(bodyParser.json({ type: 'application/*+json' }));
router.use(bodyParser.json({ type: 'application/json' }));

const unknownError = (err) => {
	const stackId = new Date().getTime();
	let errorLoggingFolder = config().error_logs_folder;
	errorLoggingFolder = !["/", "\\"].includes(errorLoggingFolder.at(-1))
		? errorLoggingFolder + "/"
		: errorLoggingFolder;
	fs.writeFileSync(
		`${errorLoggingFolder}error_${stackId}.log`,
		`ERROR:
Date: ${new Date()}
Name: ${err.name}
Message: ${err.message}
Stack:
${err.stack}`,
	);

	return {
		error: "UNKNOWN_ERROR",
		details: {
			trace_id: stackId,
		},
	};
};

// Загрузка музыки при помощи спец. метода
router.get('/music', async (req, res) => {
	res.setHeader("Content-Type", "audio/mpeg");
	database.music.findAll({
		where: { id: !Number.isInteger(+req.query.id) ? 0 : +req.query.id }, raw: true 
	}).then((data) => {
		data = data[0]?.data;
		res.send(!data ? Buffer.from([]) : data);
	}).catch((err) => {
		res.send(Buffer.from([]));
	});
});
// middleware (Обработка ошибок типа ответа)
router.use((req, res, next) => {
	const unknownResponseFormat = "UNKNOWN_RESPONSE_FORMAT";
	if (!res.result) {
		return res.status(400).send(unknownResponseFormat);
	}
	next();
	
	/*if (!req.query.response_format) {
		res.send(unknownResponseFormat);
	}
	else if (req.query.response_format === 'json') {
		res.result = function (data, isErr = false, code = 200) {
			this.status(code).json(!isErr ? {
				response : data
			} : {
				error : data
			});
		};
		next();
	}
	else {
		res.send(unknownResponseFormat);
	}*/
});

// Методы
router.use(
	require('./methods')
);

// Обработка ошибок
router.use(
	async function (err, req, res, next) {
		if (err) {
			if (err.name === "ApiError") {
				req.logger.log(
					new Date(),
					req.ip,
					`Ошибка API.\n${err.stack}`,
					true
				);
				return res.result({
					error   : err.message,
					details : err.details
				}, true, 400);
			}
			else {
				req.logger.log(
					new Date(),
					req.ip,
					`Критическая ошибка API\n${err.stack}`,
					true
				);
				return res.result({
					error : unknownError(err)
				}, true, 500);
			}
		}
		else next();
	}
);

module.exports = router;
