const ApiError = require("../errorClass");

async function checkSyntaxArgs(req, res) {
	return !!(
		// Проверка поля offset
		(req.query.id === undefined ? true : Number.isInteger(+req.query.offset)) && // Проверка поля offset
		(req.query.offset === undefined
			? true
			: Number.isInteger(+req.query.offset)) && // Проверка поля count
		(req.query.count === undefined
			? true
			: Number.isInteger(+req.query.count)) && // Проверка поля min_date
		(req.query.min_date === undefined
			? true
			: Number.isInteger(+req.query.min_date)) && // Проверка поля max_date
		(req.query.max_date === undefined
			? true
			: Number.isInteger(+req.query.max_date)) && // Проверка поля q. (Ключевые слова для поиска)
		true // (Проверки нет, query всегда строка, необязательный параметр)
	);
}

module.exports = async (req, res) => {
	if (req.method !== "GET") {
		throw new ApiError("METHOD_MUST_BE_GET", {
			request_method: req.method,
		});
	}
	if (!(await checkSyntaxArgs(req, res))) {
		throw new ApiError("INVALID_OR_UNSYNTAX_PARAMS", {
			request_method: req.method,
			params: {
				id: req.query?.id === undefined ? null : req.query.id,
				q: req.query?.q === undefined ? null : req.query.q,
				offset: req.query?.offset === undefined ? null : req.query.offset,
				count: req.query?.count === undefined ? null : req.query.count,
				min_date: req.query?.min_date === undefined ? null : req.query.min_date,
				max_date: req.query?.max_date === undefined ? null : req.query.max_date,
			},
		});
	}

	const offset = req.query.offset === undefined ? 0 : +req.query.offset;
	const countFromNull =
		req.query.count === undefined ? undefined : offset + +req.query.count;

	let result = (
		await global.database.authors.promiseMode().get(
			req.query.id === undefined
				? {}
				: {
						id: +req.query.id,
				  },
		)
	).map((i) => ({
		id: i.id,
		name: i.name,
		date: i.time,
	}));
	// Если просят выборку по времени
	if (req.query.min_date || req.query.max_date) {
		const minDate = req.query.min_date === undefined ? 0 : +req.query.min_date;
		const maxDate =
			req.query.max_date === undefined ? 1e32 : +req.query.max_date;

		result = result.filter((res) => minDate <= res.date && res.date <= maxDate);
	}

	if (req.query?.q !== undefined) {
		result = result.filter((i) => {
			const search = req.query.q.toLowerCase();
			return i.name.toLowerCase().includes(search);
		});
	}

	result = result.slice(offset, countFromNull);
	return {
		count: result.length,
		items: result,
	};
};