import _ from "lodash";

import { executeQuery } from "~/lib/db";
import helper from "~/functions/helper";
import cache from "~/functions/cache";
import itemsService from "~/services/item/items";

async function getList(category = "") {
	if (["", "weapons", "armor", "clothing", "decor"].indexOf(category) === -1) {
		throw "Category out of range";
	}

	const cachekey = `categoriesList_${category}`;
	const itemListAll = await itemsService.getList(0);

	let list = null;

	if (cache.has(cachekey)) {
		list = cache.get(cachekey);
	} else {
		let query = `
			select
				itemCategoryID,
				itemCategory,
				sortOrder,
				image
			from
				item_categories
		`;

		if (category !== "") {
			query += ` where lower(itemCategory)='${category.replace("weapons", "weapon")}'`;
		}

		query += ` order by sortOrder, itemCategory`;

		// console.log("category", category, "\nquery:", query);

		const itemCategoriesQuery = await executeQuery({ query });

		const itemSubCategoriesQuery = await executeQuery({
			query: `
				select
					itemSubCategoryID,
					itemSubCategory,
					itemCategoryID,
					sortOrder,
					image
				from
					item_subcategories
				order by
					sortOrder,
					itemSubCategory
			`,
		});
		const itemGroupsQuery = await executeQuery({
			query: `
				select
					itemGroupID,
					itemGroupName,
					itemSubCategoryID,
					sortOrder,
					image
				from
					item_groups
				order by
					sortOrder,
					itemGroupName
			`,
		});
		const itemSubGroupsQuery = await executeQuery({
			query: `
				select
					itemSubGroupID,
					itemSubGroupName,
					itemGroupID,
					sortOrder,
					image
				from
					item_subgroups
				order by
					sortOrder,
					itemSubGroupName
			`,
		});

		// console.log(itemCategoriesQuery);

		const tempList = itemCategoriesQuery.map((cat) => {
			cat.subCategories = itemSubCategoriesQuery.filter((x) => x.itemCategoryID === cat.itemCategoryID);

			_.forEach(cat.subCategories, (subcategory) => {
				subcategory.groups = itemGroupsQuery.filter((x) => x.itemSubCategoryID === subcategory.itemSubCategoryID);
				// subcategory.items = itemListAll.filter(
				// 	(x) =>
				// 		x.itemSubCategoryID === subcategory.itemSubCategoryID,
				// );

				_.forEach(subcategory.groups, (group) => {
					group.subgroups = itemSubGroupsQuery.filter((x) => x.itemGroupID === group.itemGroupID);
					if (group?.subgroups?.length === 0) {
						group.items = itemListAll.filter((x) => x.itemGroupID === group.itemGroupID);
					}

					_.forEach(group.subgroups, (subgroup) => {
						subgroup.items = itemListAll.filter((x) => x.itemSubGroupID === subgroup.itemSubGroupID);
					});

					return group;
				});

				return subcategory;
			});

			return cat;
		});

		list = helper.emptyOrRows(tempList);

		cache.set(cachekey, list);
	}

	return list;
}

export default {
	getList,
};
