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

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

	const patchables = {
		"remarks": "UPDATE preplot_lines SET remarks = $2 WHERE line = $1 AND class ='V';",
		"meta": "UPDATE preplot_lines SET meta = $2 WHERE line = $1 AND class ='V';",
		"ntba": "UPDATE preplot_lines SET ntba = $2 WHERE line = $1 AND class ='V';",
		"complete": "UPDATE preplot_points pp SET ntba = $2 FROM preplot_points_count ppc WHERE pp.line = ppc.line AND pp.point = ppc.point AND pp.line = $1 AND ($2 = false OR ppc.count = 0);"
		// NOTE on the "complete" query: if complete is true it sets *only* virgin points to NTBA=true,
		// but if complete is false it sets all points on the line to NTBA=false.
	};

	try {
		transaction.begin(client);
		for (const key in payload) {
			const text = patchables[key];
			const values = [ line, 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;
