/** Check permission to read or write certain keys.
 *
 * The global and survey `info` tables can be used to
 * store and retrieve arbitrary data, but it is also
 * used by the software, with some keys being reserved
 * for specific purposes.
 *
 * This module lists those keys which are in some way
 * reserved and reports on who should be allowed what
 * type of access to them.
 */


/** Reserved keys.
 *
 * The structure of this dictionary is
 * object.verb.subject = Boolean.
 *
 * The special value `_` is a wildcard
 * denoting the default condition for
 * a verb or a subject.
 */
const dictionary = {
	version: {
		// Database or schema version string.
		// Everyone can read, nobody can alter.
		get: { _: true  },
		_  : { _: false }
	},
	config: {
		// Configuration (site-wide or survey)
		// Nobody except admin can access
		_: { _: false, edit: true }
	},
	qc: {
		// QC results (survey)
		// Everyone can read, nobody can write
		get: { _: true  },
		_  : { _: false }
	},
	equipment: {
		// Equipment info (site)
		// Everyone can read, user + admin can alter
		get: { _: true },
		_  : { _: false, write: true, edit: true }
	},
	contact: {
		// Contact details (basically an example entry)
		// Everyone can read, admin can alter
		get: { _: true },
		_  : { _: false, edit: true },
	}
}

/** Check if access is allowed to an info entry.
 *
 * @a key {String} is the object of the action.
 * @a verb {String} is the action.
 * @a operations {Array} is one of the subjects of the action.
 *
 * @returns {Boolean} `true` is the action is allowed,
 * `false` if it is not.
 *
 * By default, all actions are allowed on a key that's
 * not listed in the dictionary. For a key that is listed,
 * the result for a default action or subject is denoted
 * by `_`, others are entered explicitly.
 *
 */
function checkPermission (key, verb, operations) {
	const entry = dictionary[key]
	if (entry) {
		const action = entry[verb] ?? entry._
		if (action) {
			for (const op of operations) {
				if ((op in action)) {
					return action[op];
				}
			}
			return action._ ?? false;
		}
		return false;
	}
	return true;
}


module.exports = checkPermission;
