"use strict";

const wrapError = require("@validatem/wrap-error");
const required = require("@validatem/required");
const anyProperty = require("@validatem/any-property");
const isString = require("@validatem/is-string");
const isPlainObject = require("@validatem/is-plain-object");

const isNotAnASTNode = require("../is-not-an-ast-node");

module.exports = function (operations) {
	const isCondition = require("./is-condition")(operations);
	const wrapPossiblyRemoteFieldName = require("./wrap-possibly-remote-field-name")(operations);

	function wrapWhereObject(fields) {
		let expressions = Object.entries(fields).map(([ key, value ]) => {
			return operations.expression({
				left: wrapPossiblyRemoteFieldName(key),
				condition: value
			});
		});
	
		return operations.allOf(expressions);
	}

	let isConditionsMapping = anyProperty({
		// NOTE: We cannot wrap the key as a field name object here, since object keys can only be strings; we do so within wrapWhereObject instead
		key: [ required, isString ],
		value: [ required, isCondition ]
	});

	let rules = [ isPlainObject, isNotAnASTNode, isConditionsMapping, wrapWhereObject ];

	return wrapError("Must be an object of WHERE conditions", rules, { preserveOriginalErrors: true });
};
