import { createTimeoutRecord } from "db/dbTimeouts";
import { createUsedItemRecord } from "db/dbUsedItems";
import { getUserRecord } from "db/dbUser";
import { changeItemCount, Item } from "items";
import { sendMessage } from "lib/commandUtils";
import parseCommandArgs from "lib/parseCommandArgs";
import { redis } from "lib/redis";
import { timeout } from "lib/timeout";
import { streamerId } from "main";
import User from "user";
import { playAlert } from "web/alerts/serverFunctions";

const ITEMNAME = "silverbullet";

export default new Item({
	name: ITEMNAME,
	prettyName: "Silver bullet",
	plural: "s",
	description: "Times targeted or random vulnerable user out for 30 minutes",
	aliases: ["execute", "silverbullet"],
	specialaliases: ["blastin"],
	price: 666,
	execution: async (msg, user, specialargs) => {
		const messagequery = parseCommandArgs(
			msg.messageText,
			specialargs?.activation,
		);

		if (await user.itemLock()) {
			await sendMessage("Cannot use an item (itemlock)", msg.messageId);
			return;
		}
		await user.setLock();

		const userObj = await getUserRecord(user);
		if (userObj.inventory[ITEMNAME]! < 1 && user.id !== streamerId) {
			await sendMessage(`You don't have any silver bullets!`, msg.messageId);
			await user.clearLock();
			return;
		}

		let target: User | null;
		if (!messagequery[0]) {
			const vulnsids = await redis.keys("user:*:vulnerable");
			const baseusers = vulnsids.map((a) => User.initUserId(a.slice(5, -11)));
			const users: User[] = [];
			for (const user of baseusers) {
				const a = await user;
				if (!a) continue;
				users.push(a);
			}
			if (users.length === 0) {
				await user.clearLock();
				await sendMessage("No vulnerable chatters", msg.messageId);
				return;
			}
			target = users[Math.floor(Math.random() * users.length)]!;
			await playAlert({
				name: "blastinRoulette",
				user: user.displayName,
				targets: users.map((a) => a.displayName),
				finaltarget: target.displayName,
			});
			await new Promise((res, _) => setTimeout(res, 4000));
		} else {
			target = await User.initUsername(messagequery[0].toLowerCase());
		}
		if (!target) {
			await user.clearLock();
			await sendMessage(`${messagequery[0]} doesn't exist`);
			return;
		}

		await getUserRecord(target); // make sure the user record exist in the database

		const result = await timeout(
			target,
			`You got blasted by ${user.displayName}!`,
			60 * 30,
		);
		if (result.status)
			await Promise.all([
				sendMessage(
					`KEKPOINT KEKPOINT KEKPOINT ${target.displayName.toUpperCase()} RIPBOZO RIPBOZO RIPBOZO RIPBOZO RIPBOZO RIPBOZO RIPBOZO`,
				),
				changeItemCount(user, userObj, ITEMNAME),
				createTimeoutRecord(user, target, ITEMNAME),
				createUsedItemRecord(user, ITEMNAME),
				playAlert({
					name: "userExecution",
					user: user.displayName,
					target: target.displayName,
				}),
			]);
		else {
			switch (result.reason) {
				case "banned":
					await sendMessage(
						`${target.displayName} is already timed out/banned`,
						msg.messageId,
					);
					break;
				case "illegal":
					await Promise.all([
						sendMessage(`${user.displayName} Nou Nou Nou`),
						timeout(user, "nah", 60),
					]);
					break;
				case "unknown":
					await sendMessage("Something went wrong...", msg.messageId);
					break;
			}
		}
		await user.clearLock();
	},
});
