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

/**
 * Stringify arrays.
 *
 * node-postgres has an issue in that it transforms
 * JSON array objects into PostgreSQL arrays instead
 * of JSON arrays, which causes a problem for json/jsonb
 * fields.
 *
 * Note: this is a feature not a bug. See:
 * https://github.com/brianc/node-postgres/issues/442
 */
function formatValue(value) {
	if (Array.isArray(value)) {
		return JSON.stringify(value);
	} else {
		return value;
	}
}

async function put (item_id, values) {
	const client = await pool.connect();

	const updateable = [ "status", "results", "parent_id" ];
	const fields = [];
	const params = [item_id];

	for (const field of updateable) {
		if (field in values) {
			fields.push(`${field} = $${params.length+1}`);
			params.push(formatValue(values[field]));
		}
	}

	const text = `
		UPDATE queue_items
		SET
			${fields.join(",\n")}
		WHERE item_id = $1
		RETURNING *;
	`;

	const res = await client.query(text, params);
	client.release();
	return res.rows[0];
}

module.exports = put;
