import _ from "lodash";
import { executeQuery } from "~/lib/db";
import svcSubGroups from "~/services/item/subGroups";
import helper from "~/functions/helper";

import cache from "~/functions/cache";

async function getList(itemSubCategoryID = "0") {
	if (["0", "2", "5"].indexOf(itemSubCategoryID) === -1) {
		throw "ItemSubCategoryID out of range";
	}

	const cachekey = `groupsList${itemSubCategoryID}`;

	// console.log("CHECK CACHE KEY:", cachekey);

	let list = null;

	if (cache.has(cachekey)) {
		// console.log('  >> get cached groups list')
		list = cache.get(cachekey);
	} else {
		let query = `
			select
				*
			from
				item_groups
		`;

		if (itemSubCategoryID !== "0") {
			query += ` where itemSubCategoryID=${itemSubCategoryID}`;
		}

		query += ` order by sortOrder, itemGroupName`;

		const rows = await executeQuery({ query });

		// const tempList = await executeQuery({
		// 	query: `
		// 	select
		// 		*
		// 	from
		// 		item_groups
		// 	order by
		// 		sortOrder,
		// 		itemGroupName
		// `,
		// });
		const itemSubGroups = await svcSubGroups.getList();

		list = helper.emptyOrRows(rows);

		if (list.length > 0 && itemSubGroups.length > 0) {
			for (let x = 0; x < list.length; x++) {
				list[x].itemSubGroups =
					_.filter(
						itemSubGroups,
						(y) => y.itemGroupID === list[x].itemGroupID,
					) || [];
			}
		}

		cache.set(cachekey, list);
	}

	// const meta = { page };

	// console.log('  >> return groups list length', list.length)

	return list;
	// return {
	// 	list,
	// 	meta,
	// }
}

export default {
	getList,
};
