const fs = require('fs');
const path = require('path');
const https = require('https');
const fetch = require('node-fetch');
const DOUGAL_ROOT = require('../../lib/config').DOUGAL_ROOT;
const cfg = require('../../lib/config').global.queues.asaqc.request;

/**
 * Return a suitably configured httpsAgent with the client's TLS
 * credentials if given.
 */
function httpsAgent () {
	// References:
	// https://github.com/node-fetch/node-fetch/issues/904
	// https://nodejs.org/api/https.html#https_https_request_options_callback

	if (!cfg.httpsAgent) {
		return;
	}

	const options = {
		key: fs.readFileSync(path.resolve(DOUGAL_ROOT, cfg.httpsAgent.key)),
		cert: fs.readFileSync(path.resolve(DOUGAL_ROOT, cfg.httpsAgent.cert))
	}

	return https.Agent(options);
}


/**
 * Send a payload to the ASAQC `upload-file-encoded` endpoint.
 * https://api.equinor.com/docs/services/vessel-track/operations/FileUploadEncoded
 */
async function despatchPayload(payload) {
	cfg.args.headers["Ocp-Apim-Subscription-Key"] = process.env.DOUGAL_ASAQC_SUBSCRIPTION_KEY;

	try {
		const res = await fetch(cfg.url, {
			...cfg.args,
			body: JSON.stringify(payload),
			agent: httpsAgent()
		});

		if (res) {
			return await res.json();
		} else {
			console.error("NO RESPONSE FROM ASAQC ENDPOINT");
		}
	} catch (err) {
		console.error(err);
		return {error: err};
	}
}


module.exports = despatchPayload;
