function parseBoolFromString(string) {
	if (string === 'true') {
		return true;
	}

	if (string === 'false') {
		return false;
	}

	return string;
}

function parseValue(value) {
	if (typeof value === 'string') {
		return parseBoolFromString(value);
	}

	if (Array.isArray(value)) {
		return value.map(parseValue);
	}

	if (value && typeof value === 'object') {
		return parseObject(value);
	}

	return value;
}

function parseObject(obj) {
	return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, parseValue(value)]));
}

// Express 5's req.query is a getter that re-parses the URL on every access, so it can no longer
// be reassigned like `req.query = ...` (that's a silent no-op); it must be shadowed with its own
// property on the request instance instead. See https://github.com/expressjs/express/issues/6633
export default function queryBoolean() {
	return (req, _res, next) => {
		Object.defineProperty(req, 'query', {
			value: parseObject(req.query),
			configurable: true,
			enumerable: true,
			writable: true,
		});

		next();
	};
}
