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

async function patch (projectId, sequence, payload, opts = {}) {
	const client = await setSurvey(projectId);

	const patchables = {
		"remarks": "UPDATE raw_lines SET remarks = $2 WHERE sequence = $1;",
		"remarks_final": "UPDATE final_lines SET remarks = $2 WHERE sequence = $1;",
		"meta": "UPDATE raw_lines SET meta = $2 WHERE sequence = $1;",
		"meta_final": "UPDATE final_lines SET meta = $2 WHERE sequence = $1;"
	};

	try {
		transaction.begin(client);
		for (const key in payload) {
			const text = patchables[key];
			const values = [ sequence, payload[key] ];

			if (!text) {
				throw {status: 400, message: "Invalid patch" };
			}

			await client.query(text, values);
		}
		transaction.commit(client);
	} catch (err) {
		transaction.rollback(err);
		throw err;
	} finally {
		client.release();
	}
}

module.exports = patch;
