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

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

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

	try {
		const text = jsonpath.length
			? `
				INSERT INTO info (key, value)
				VALUES ($2, jsonb_insert('${isNaN(Number(jsonpath[0])) ? "{}" : "[]"}'::jsonb, $3, $1))
				ON CONFLICT (key) DO UPDATE
					SET
						key = $2,
						value = jsonb_insert((SELECT value FROM info WHERE key = $2), $3, $1, true)
				RETURNING *;
			`
			: `
				INSERT INTO info (key, value)
				VALUES ($2, jsonb_insert('[]'::jsonb, '{0}', $1))
				ON CONFLICT (key) DO UPDATE
					SET
						key = $2,
						value = jsonb_insert((SELECT value FROM info WHERE key = $2), '{-1}'::text[], $1, true)
				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);
		if (err.code == 22023) {
			throw {status: 400, message: "Cannot post to non-array"};
		} else {
			throw err;
		}
	} finally {
		client.release();
	}
}

module.exports = post;
