import { Command, type commandOptions } from "lib/commandUtils";
import type User from "user";

export type items = "blaster" | "silverbullet" | "grenade" | "tnt";

interface itemOptions extends Omit<commandOptions, "usertype"> {
	name: items;
	prettyName: string;
	plural: string;
	description: string;
	price: number;
}

export class Item extends Command {
	public readonly name: items = "blaster";
	public readonly prettyName: string;
	public readonly plural: string;
	public readonly description: string;
	public readonly price: number;

	/** Creates an item object */
	constructor(options: itemOptions) {
		super({
			...options,
			usertype: "chatter", // Everyone can use items
			disableable: true, // Items can always be disabled
		});
		this.name = options.name;
		this.prettyName = options.prettyName;
		this.plural = options.plural;
		this.description = options.description;
		this.price = options.price;
	}
}

import { readdir } from "node:fs/promises";
import { type UserRecord, updateUserRecord } from "db/dbUser";

const itemAliasMap = new Map<string, Item>();
const itemObjectArray: Item[] = [];
const specialAliasItems = new Map<string, Item>();
const emptyInventory: inventory = {};
const itemarray: items[] = [];

const files = await readdir(import.meta.dir);
for (const file of files) {
	if (!file.endsWith(".ts")) continue;
	if (file === import.meta.file) continue;
	const item: Item = await import(
		`${import.meta.dir}/${file.slice(0, -3)}`
	).then((a) => a.default);
	emptyInventory[item.name] = 0;
	itemarray.push(item.name);
	itemObjectArray.push(item);
	for (const alias of item.aliases) {
		itemAliasMap.set(alias, item); // Since it's not a primitive type the map is filled with references to the item, not the actual object
	}
	for (const alias of item.specialaliases) {
		specialAliasItems.set(alias, item);
	}
}

export default itemAliasMap;
export { emptyInventory, itemarray, specialAliasItems, itemObjectArray };

export type inventory = {
	[key in items]?: number;
};

export async function changeItemCount(
	user: User,
	userRecord: UserRecord,
	itemname: items,
	amount = -1,
): Promise<false | UserRecord> {
	userRecord.inventory[itemname] = userRecord.inventory[itemname]! += amount;
	if (userRecord.inventory[itemname] < 0) return false;
	await updateUserRecord(user, userRecord);
	return userRecord;
}
