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

async function del (projectId, sequenceId, opts = {}) {
	const client = await setSurvey(projectId);

	await transaction.begin(client);

	if (sequenceId) {

		const queries = [
			`
				UPDATE raw_lines
				SET meta = meta - 'lastQCHash'
				WHERE sequence = $1;
			`,
			`
				DELETE
				FROM event_log_full
				WHERE
					sequence = $1 AND meta ? 'qc_id';
			`,
			`
				UPDATE info
				SET value = value - 'hash'
				WHERE key = 'qc'
				-- Consume the parameter that we are passing
				AND $1 = $1;
			`
		];

		const values = [ sequenceId ];

		for (const text of queries) {
			await client.query(text, values);
		}

	} else {

		const queries = [
			`
				UPDATE raw_lines
				SET meta = meta - 'lastQCHash';
			`,
			`
				DELETE
				FROM event_log_full
				WHERE
					meta ? 'qc_id';
			`,
			`
				UPDATE info
				SET value = value - 'hash'
				WHERE key = 'qc';
			`
		];

		for (const text of queries) {
			await client.query(text);
		}

	}

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

	return;
}

module.exports = del;
