const { setSurvey } = require('../../connection');
const { deepMerge, removeNulls } = require('../../../utils');
const { modify } = require('../create');


async function put (projectId, payload, opts = {}) {
	let client;
	try {
		client = await setSurvey(); // Use public schema

		const text = `
			SELECT meta
			FROM projects
			WHERE pid = $1;
		`;

		const res = await client.query(text, [projectId]);

		const source = res.rows[0].meta;

		if (!source) {
			throw { status: 404, message: "Not found" };
		}

		console.log("PAYLOAD ID", payload.id, typeof payload);
		if (("id" in payload) && (projectId.toLowerCase() != payload.id.toLowerCase())) {
			throw {
				status: 422,
				message: "Project ID cannot be changed in this Dougal version"
			}
		}

		if (("name" in payload) && source.name && (source.name != payload.name)) {
			throw {
				status: 422,
				message: "Project name cannot be changed in this Dougal version"
			}
		}

		// We do not allow users to change the schema
		delete payload.schema;

		const dest = removeNulls(payload);
		await modify(projectId, dest);
		return dest;

	} catch (err) {
		if (err.code == "42P01") {
			throw { status: 404, message: "Not found" };
		} else {
			throw err;
		}
	} finally {
		client.release();
	}
}

module.exports = put;
