const { setSurvey, pid2schema, pool } = require('../connection');
const event = require('../event');
const getSummary = require('./summary').get;

// Returns true if the project has no
// preplots, sequences or log entries,
// or if the project ID is not found
// in the database.
async function isDeletable (projectId) {
	let summary;

	try {
		summary = await getSummary(projectId);
	} catch (err) {
		if (err.code == "42P01") {
			// Project does not exist
			return true;
		} else {
			throw err;
		}
	}

	if (!summary) {
		// projectId does not exist in the database
		return true;
	}

	if (summary.total == 0 && summary.seq_raw == 0 && summary.seq_final == 0 && !summary.prod_duration) {
		// Check for existing events (excluding deleted)
		const events = await event.list(projectId, {limit: 1});
		return events.length == 0;
	}
	return false;
};

async function del (projectId, opts = {}) {
	if (await isDeletable(projectId)) {
		const schema = await pid2schema(projectId);
		if (schema) {
			// NOTE: Should be reasonably safe as `schema` is not
			// under user control.
			const sql = `
				DROP SCHEMA ${schema} CASCADE;
				DELETE FROM public.projects WHERE schema = '${schema}';

			`;
			console.log(sql);
			await pool.query(sql);
		}
		// We don't care if schema does not exist
	} else {
		throw { status: 405, message: "Project is not empty" }
	}
}

module.exports = del;
