import { Cheer } from "cheers";
import { createCheerEventRecord } from "db/dbCheerEvents";
import { createGetLootRecord } from "db/dbGetLoot";
import { getUserRecord, updateUserRecord } from "db/dbUser";
import itemMap, { type inventory, type items } from "items";
import { sendMessage } from "lib/commandUtils";
import { redis } from "lib/redis";
import { timeout } from "lib/timeout";

export default new Cheer({
	name: "superloot",
	amount: 150,
	isItem: true,
	async execute(msg, user) {
		if (!(await redis.exists("streamIsLive"))) {
			await sendMessage(`No loot while stream is offline`, msg.messageId);
			return;
		}
		if (await user.itemLock()) {
			await sendMessage(`Cannot get loot (itemlock)`, msg.messageId);
			return;
		}
		await user.setLock();
		const userData = await getUserRecord(user);

		await sendMessage("HOLD");
		await new Promise((res) => setTimeout(res, 1000 * 5));

		if (Math.random() > 0.5) {
			await Promise.all([
				sendMessage(
					`SUPERLOOT FAILED!!! KEKPOINT KEKPOINT KEKPOINT ${msg.chatterDisplayName.toUpperCase()} SEE YOU IN 5 MINUTES!!!`,
				),
				timeout(user, `RIP BOZO! NO SUPERLOOT FOR YOU`, 60 * 5),
				user.clearLock(),
			]);
			return;
		}

		const gainedqbucks = Math.floor(Math.random() * 250) + 150; // range from 150 to 400
		userData.balance += gainedqbucks;

		const itemDiff: inventory = {
			grenade: 0,
			blaster: 0,
			tnt: 0,
			silverbullet: 0,
		};

		for (let i = 0; i < 15; i++) {
			if (Math.floor(Math.random() * 5) === 0) itemDiff.grenade! += 1; // 1 in 5
			if (Math.floor(Math.random() * 5) === 0) itemDiff.blaster! += 1; // 1 in 5
			if (Math.floor(Math.random() * 50) === 0) itemDiff.tnt! += 1; // 1 in 50
			if (Math.floor(Math.random() * 50) === 0) itemDiff.silverbullet! += 1; // 1 in 50
		}

		for (const [item, amount] of Object.entries(itemDiff) as [
			items,
			number,
		][]) {
			if (userData.inventory[item]) userData.inventory[item] += amount;
			else userData.inventory[item] = amount;
		}

		const itemstrings: string[] = [`${gainedqbucks} qbucks`];

		for (const [item, amount] of Object.entries(itemDiff)) {
			if (amount === 0) continue;
			const selection = itemMap.get(item);
			if (!selection) continue;
			itemstrings.push(
				`${amount} ${selection.prettyName + (amount === 1 ? "" : selection.plural)}`,
			);
		}

		const last = itemstrings.pop();
		const itemstring =
			itemstrings.length === 0 ? last : `${itemstrings.join(", ")} and ${last}`;
		const message = `You got ${itemstring}`;

		await Promise.all([
			updateUserRecord(user, userData),
			sendMessage(message, msg.messageId),
			createCheerEventRecord(user, "superloot"),
			createGetLootRecord(user, gainedqbucks, itemDiff, "superloot"),
			user.clearLock(),
		]);
	},
});
