const fetch = require('node-fetch');
const cfg = require("./config");

const defaultOptions = {
	title: "HTTP backend failure",
	description: null,
	service: `backend (NODE_ENV=${process.env.NODE_ENV})`,
	severity: "critical",
	hosts: process.env.HOST
};

function send (options = {}) {

	let url, authkey;
	try {

		url = cfg.global.webhooks.alert.url;
		authkey = process.env.GITLAB_ALERTS_AUTHKEY || cfg.global.webhooks.alert.authkey;

		if (!url) return;

	} catch (err) {
		if (!(err instanceof TypeError)) {
			console.error("Alert failed with error", err);
		}
		return;
	}

	const opts = Object.assign({}, defaultOptions, options);
	opts.hosts = defaultOptions.hosts; // Do not allow override
	const body = JSON.stringify(opts);

	fetch(url, {
		method: "POST",
		headers: {
			"Authorization": "Bearer " + authkey,
			"Content-Type": "application/json"
		},
		body
	})
	.then(res => {
		if (res.ok && res.status == 200) {
			return;
		}
		console.error("Alert sending failed with status", res.status, res.statusText);
	})
	.catch(err => {
		console.error("Alert sending failed with error", err);
	});
}

module.exports = send;
