import { executeQuery } from "../lib/db";
import helper from "~/functions/helper";

import cache from "~/functions/cache";

async function getList(category: string) {
	if (
		["", "weapons", "armor", "clothing", "decor"].indexOf(category) === -1
	) {
		throw "Category out of range";
	}

	const cachekey = `makersList_${category}`;

	let list = null;

	if (cache.has(cachekey)) {
		list = cache.get(cachekey);
	} else {
		let query = `
			SELECT
				makerID,
				makerName
			FROM
				makers
		`;

		if (category !== "") {
			query += `
				WHERE makerID in (
					select makerID
					from makers_subcategories msc
					join item_subcategories isc on msc.subCategoryID = isc.itemSubCategoryID
					join item_categories ic on isc.itemCategoryID = ic.itemCategoryID
					where lower(itemCategory)='${category.replace("weapons", "weapon")}'
				)
			`;
		}

		query += ` ORDER BY makerName`;

		const rows = await executeQuery({ query });

		list = helper.emptyOrRows(rows);

		cache.set(cachekey, list);
	}

	return list;
}

async function getListByCategory() {
	const cachekey = "makersListByCategory";

	let list = null;

	if (cache.has(cachekey)) {
		list = cache.get(cachekey);
	} else {
		const rows = await executeQuery({
			query: `
				SELECT
					makerID,
					makerName,
					itemSubCategoryID,
					itemSubCategory,
					itemCategoryID,
					itemCategory,
					CONCAT(
						itemCategory,
						' > ',
						itemSubCategory,
						' > ',
						makerName
					) as compoundKey,
					CONCAT(
						itemCategoryID,
						'_',
						itemSubCategoryID,
						'_',
						makerID
					) as compoundID
				FROM
					vw_makers
				WHERE
					itemSubCategoryID is not NULL
				ORDER BY
					itemCategorySortOrder,
					itemSubCategorySortOrder,
					makerName
			`,
		});

		list = helper.emptyOrRows(rows);

		cache.set(cachekey, list);
	}

	return list;
}

export default {
	getList,
	getListByCategory,
};
