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

async function get (queueId/*unused*/, opts = {}) {
	const client = await pool.connect();

	const validStatuses = [
		'queued',
		'cancelled',
		'failed',
		'sent'
	];

	const validOrders = {
		created_on: "created_on",
		updated_on: "updated_on",
		not_before: "not_before",
		item_id: "item_id",
		status: "status",
		parent_id: "parent_id",
		project: "payload->'project'",
		sequence: "payload->'sequence'"
	};

	const limit = Math.min(Math.abs(opts.limit) || 100, 1000);
	const offset = Math.abs(opts.offset) || 0;
	const order = validOrders[opts.order] || "updated_on";
	const dir = (!opts.dir || opts.dir == "-")
		? "DESC"
		: "ASC";

	const validStatus = validStatuses.includes(opts.status);
	const status = validStatus ? opts.status : 1;

	const hasProject = "project" in opts;
	const hasSequence = "sequence" in opts;
	const project = hasProject
		? opts.project
		: 1;
	const sequence = hasSequence
		? opts.sequence
		: 1;

	const restrict1 = validStatus
		? "status = $3"
		: "$3 = $3";

	const restrict2 = hasProject
		? "AND payload->>'project' = $4"
		: "AND $4 = $4";

	// Yes, technically a user could restrict by sequence
	// only, without specifying a project. Let's call that
	// a feature.
	const restrict3 = hasSequence
		? "AND payload->>'sequence' = $5"
		: "AND $5 = $5";

	const text = `
		SELECT *
		FROM queue_items
		WHERE ${restrict1} ${restrict2} ${restrict3}
		ORDER BY ${order} ${dir}
		LIMIT $1
		OFFSET $2;
	`;

	const res = await client.query(text, [limit, offset, status, project, sequence]);
	client.release();
	return res.rows;
}

module.exports = get;
