const { setSurvey } = require('../../connection');
const refresh = require('./refresh');

async function get (projectId, opts = {}) {
	try {
		const client = await setSurvey(projectId);

		const text = `
			SELECT *
			FROM project_summary;
		`;

		const res = await client.query(text);
		client.release();
		return res.rows[0];
	} catch (err) {
		if (err.code == "55000") {
			// Materialised view has not been refreshed
			await refresh(projectId, opts);
			return get(projectId, opts);
		} else if (err.code == "42P01") {
			throw { status: 404, message: "Not found" };
		} else {
			throw err;
		}
	}
}

module.exports = get;
