import { stringify } from '@brillout/json-serializer/stringify';

import argv from '../argv.js';
import initLogger from '../logger.js';

const logger = initLogger();

export default function errorHandler(error, req, res, _next) {
	logger.warn(`Failed to fulfill request to ${req.path} (${error.httpCode || 500}): ${error.message}`);

	if (argv.debug) {
		logger.error(error);
	}

	if (error.httpCode) {
		res.status(error.httpCode).send(stringify({
			statusCode: error.httpCode,
			statusMessage: error.message,
		}));

		return;
	}

	res.status(500).send(stringify({
		statusCode: 500,
		statusMessage: 'Oops... our server messed up. We will be investigating this incident, our apologies for the inconvenience.',
	}));
}
