
const { transaction, pool } = require('../connection');

async function post(queueId/*unused*/, payload, parent_id) {

	// Technically the API only supports an array payload,
	// but we'll be permissive and accept a single request
	// object.
	if (!Array.isArray(payload)) {
		payload = [payload];
	}

	const client = await pool.connect();

	await transaction.begin(client);
	for (const {project, sequence} of payload) {

		if ([project, sequence].some(v => typeof v === "undefined")) {
			throw { status: 400, message: "Malformed request" };
		}

		// If we got here, the request is probably OK.
		// Most fields just take default values.
		const text = `
			INSERT INTO queue_items (payload, parent_id)
			VALUES ($1, $2);
		`;

		await client.query(text, [{project, sequence}, parent_id]);

	}
	await transaction.commit(client);
	client.release();


}

module.exports = post;
