const { makeSubscriber, pool } = require('./connection');
const { ALERT, ERROR, WARNING, NOTICE, INFO, DEBUG } = require('DOUGAL_ROOT/debug')(__filename);

async function purge () {
	DEBUG("Purging old notifications");
	const client = await pool.connect();
	try {
		await client.query("CALL purge_notifications();");
	} catch (err) {
		ERROR(err);
	} finally {
		client.release();
	}
}

async function fullPayload (payload) {

	if (!payload.payload_id) {
		return payload;
	} else {
		let client, res;
		try {
			client = await pool.connect();
			const text = `SELECT payload FROM notify_payloads WHERE id = $1;`;
			const values = [ payload.payload_id ];
			res = await client.query(text, values);
			res = res?.rows[0]?.payload;
			DEBUG(`Oversize notification payload retrieved with id ${payload.payload_id} and size ${res.length}`);
			// DEBUG(res);
			res = JSON.parse(res);
		} catch (err) {
			ERROR(err);
		} finally {
			if (client) {
				client.release();
			}
		}
		return res;
	}
}

async function listen (addChannels, callback) {

	const client = makeSubscriber();

	client.events.on("error", (err) => {
		console.error("Postgres LISTEN subscriber error", err);
		setTimeout(() => client.connect(), 5000);
	});

	client.connect();

	if (!Array.isArray(addChannels)) {
		addChannels = [addChannels];
	}

	for (const channel of addChannels) {
		await client.listenTo(channel);
		client.notifications.on(channel, async (payload) => {
			const data = {
				channel,
				_received: new Date(),
				payload: await fullPayload(payload)
			};
			callback(data);
		});
	}

	return client;
}

module.exports = {
	listen,
	purge
};
