import { Cheer } from "cheers";
import { createCheerEventRecord } from "db/dbCheerEvents";
import { createTimeoutRecord } from "db/dbTimeouts";
import { getUserRecord } from "db/dbUser";
import { sendMessage } from "lib/commandUtils";
import { parseCheerArgs } from "lib/parseCommandArgs";
import { redis } from "lib/redis";
import { timeout } from "lib/timeout";
import User from "user";
import { playAlert } from "web/alerts/serverFunctions";

export default new Cheer({
	name: "realsilverbullet",
	amount: 6666,
	isItem: false,
	async execute(msg, user) {
		const args = parseCheerArgs(msg.messageText);

		let target: User | null;
		if (!args[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 sendMessage("No vulnerable chatters, -6666 KEKPOINT");
				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(args[0].toLowerCase());
		}
		if (!target) {
			await sendMessage("dumbass wasted 6666 bits KEKPOINT", msg.messageId);
			return;
		}
		await getUserRecord(target);

		const result = await timeout(
			target,
			`You got fucking DELETED by ${user.displayName}!`,
			60 * 60 * 24,
		);
		if (result.status)
			await Promise.all([
				sendMessage(
					`KEKPOINT KEKPOINT KEKPOINT ${target.displayName.toUpperCase()} RIPBOZO RIPBOZO RIPBOZO RIPBOZO RIPBOZO RIPBOZO RIPBOZO`,
				),
				createTimeoutRecord(user, target, "realsilverbullet"),
				createCheerEventRecord(user, "realsilverbullet"),
				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 * 60 * 24),
					]);
					break;
				case "unknown":
					await sendMessage("Something went wrong... oops", msg.messageId);
					break;
			}
		}
	},
});
