const { setSurvey, transaction } = require('../connection');
const checkPermission = require('./check-permission');

async function del (projectId, path, opts = {}, operations = []) {
	const client = await setSurvey(projectId);
	const [key, ...jsonpath] = (path||"").split("/").filter(i => i.length);

	if (!checkPermission(key, "delete", operations)) {
		throw {status: 403, message: "Forbidden"};
		return;
	}

	try {
		const text = jsonpath.length
			? `
				UPDATE info
					SET value = value #- $2
				WHERE key = $1;
			`
			: `
				DELETE FROM info
				WHERE key = $1;
			`;
		const values = jsonpath.length ? [key, jsonpath] : [key];
		await client.query(text, values);
	} catch (err) {
		console.error("ERROR", err);
		throw err;
	} finally {
		client.release();
	}
}

module.exports = del;
