import helper from "~/functions/helper";
import { executeQuery } from "~/lib/db";
import _ from "lodash";

// import cache from "~/functions/cache";

import svcItems from "~/services/item/items";

// const itemType = "itemSet";

async function getList(category: string = "") {
	const categoryType = category.toUpperCase().substring(0, 1);
	// const cacheKey = `${itemType}_${categoryType}`;

	// (W)eapons
	// (A)rmor
	// (D)ecor
	// empty string
	if (categoryType !== "" && categoryType !== "W" && categoryType !== "A" && categoryType !== "D") {
		throw "Invalid category";
	}

	let list = null;

	// if (cache.has(cacheKey)) {
	// 	list = cache.get(cacheKey);
	// } else {
	let query = `
			SELECT
				*
			FROM
				vw_itemsets
        `;

	if (categoryType !== "") {
		query += ` WHERE itemSetCategory = '${categoryType}'`;
	}

	query += " ORDER BY purchasedDate desc, makerName asc";

	const rows = await executeQuery({ query });

	let allItems = [];

	if (categoryType === "W") {
		allItems = await svcItems.getList(1);
	} else if (categoryType === "A") {
		allItems = await svcItems.getList(2);
	} else if (categoryType === "D") {
		allItems = await svcItems.getList(4);
	}

	// console.log(allItems);

	// const itemsInSet = await getItems(10);
	// console.log("add one", itemsInSet.length);

	// rows.forEach(async (row) => {
	for (const row of rows) {
		// console.log(row.itemSetID);
		// row.items = allItems.filter((x) => x.itemSetID.toString() === row.itemSetID.toString());
		// row.items = itemsInSet;
		const itemsInSet = await getItems(row.itemSetID);
		// // console.log(row.itemSetID, "add one", itemsInSet);
		row.items = itemsInSet || [];
	}

	// console.log("rows:", rows);

	list = helper.emptyOrRows(rows);

	// cache.set(cacheKey, list);
	// }

	return list;
}

async function getOne(itemSetID: string) {
	const list = await getList();
	const one = _.find(list, (row) => row.itemSetID.toString() === itemSetID);

	return one;
}

async function getItems(itemSetID: string) {
	const query = `
		SELECT
			*
		FROM
			vw_items
		WHERE
			itemSetID=${itemSetID}
	`;

	const items = await executeQuery({ query });

	return items;
}

export default {
	getList,
	getOne,
	getItems,
};
