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

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

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

	try {
		const text = jsonpath.length
			? `
				INSERT INTO info (key, value)
				VALUES ($2, jsonb_set('${isNaN(Number(jsonpath[0])) ? "{}" : "[]"}'::jsonb, $3, $1))
				ON CONFLICT (key) DO UPDATE
					SET
						key = $2,
						value = jsonb_set((SELECT value FROM info WHERE key = $2), $3, $1)
				RETURNING *;
			`
			: `
				INSERT INTO info (key, value)
				VALUES ($2, $1)
				ON CONFLICT (key) DO UPDATE
					SET
						key = $2,
						value = $1
				RETURNING *;
			`;
		const values = jsonpath.length ? [JSON.stringify(payload), key, jsonpath] : [JSON.stringify(payload), key];
		await client.query(text, values);
	} catch (err) {
		console.error("ERROR", err);
		throw err;
	} finally {
		client.release();
	}
}

module.exports = put;
