import { executeQuery } from "~/lib/db";
import helper from "~/functions/helper";
import cache from "~/functions/cache";

async function getList(itemCategoryID = "0") {
	if (["0", "1", "2", "3", "4"].indexOf(itemCategoryID) === -1) {
		throw "Item Category ID out of range";
	}

	const cachekey = `subCategoriesList${itemCategoryID}`;

	let list = null;

	if (cache.has(cachekey)) {
		list = cache.get(cachekey);
	} else {
		let query = `
			select
				*
			from
				item_subcategories
		`;

		if (itemCategoryID !== "0") {
			query += ` where itemCategoryID=${itemCategoryID}`;
		}

		query += ` order by itemCategoryID, sortOrder, itemSubCategory`;

		const rows = await executeQuery({ query });

		list = helper.emptyOrRows(rows);

		cache.set(cachekey, list);
	}

	return list;
}

export default {
	getList,
};
