"use strict";

const { validateArguments } = require("@validatem/core");

const node = require("../ast-node");

module.exports = function count(operations) {
	const isCollection = require("../validators/operations/is-collection")(operations);

	return function count(_collection) {
		let [ collection ] = validateArguments(arguments, {
			collection: [ isCollection ]
		});

		// TODO: Investigate whether this can be made more performant by counting a specific field rather than *. That would probably require stateful knowledge of the database schema, though.
		let fieldReference = (collection != null)
			? operations.remoteField({ collection: collection, field: "*" }) // FIXME: Make sure not to break this (internally) when making field name checks more strict
			: operations.field("*");

		return node({
			type: "aggregrateFunction",
			functionName: "count",
			args: [ fieldReference ]
		});
	};
};
