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

async function post (projectId, payload, opts = {}) {

	const client = await setSurvey(projectId);
	try {

		if (!payload.sequence) {
			payload.sequence = await lib.getSequence(client);
		}
		// if (!payload.ts0 || !payload.ts1) {
		// 	const ts = await lib.getTimestamps(client, projectId, payload);
		// 	if (!payload.ts0) {
		// 		payload.ts0 = ts.ts0;
		// 	}
		// 	if (!payload.ts1) {
		// 		payload.ts1 = ts.ts1;
		// 	}
		// }
		const name = await lib.getLineName(client, projectId, payload);

		return name;
	} catch (err) {
		if (err.code && Math.trunc(err.code/1000) == 23) {
			// Class 23 — Integrity Constraint Violation
			console.error(err);
			throw { status: 400, message: "Malformed request" };
		} else {
			throw err;
		}
	} finally {
		client.release();
	}

	return;
}

module.exports = post;
