"use strict";

const { validateArguments } = require("@validatem/core");
const required = require("@validatem/required");
const anyProperty = require("@validatem/any-property");
const isString = require("@validatem/is-string");

const unreachable = require("../unreachable");
const node = require("../ast-node");
const tagAsType = require("../validators/tag-as-type");

module.exports = function (operations) {
	const isComputable = require("../validators/operations/is-computable")(operations);

	return function compute(_items) {
		let [ items ] = validateArguments(arguments, {
			// FIXME: Add support for scalar compute
			// items: [ required, either([
			// 	[ isComputable, tagAsType("single") ],
			// 	[ anyProperty({
			// 		key: [ required, isString ],
			// 		value: [ required, isComputable ]
			// 	}), tagAsType("multiple") ]
			// ]) ]
			items: [ required, anyProperty({
				key: [ required, isString ],
				value: [ required, isComputable ]
			}), tagAsType("multiple") ]
		});

		if (items.type === "multiple") {
			return node({
				type: "computeMultiple",
				items: Object.entries(items.value).map(([ key, value ]) => {
					return node({
						type: "compute",
						field: operations.field(key),
						expression: value
					});
				})
			});
		} else {
			unreachable(`Invalid tagged type '${items.type}'`);
		}
	};
};
