import type { EventSubChannelChatMessageEvent } from "@twurple/eventsub-base";
import { createAnivTimeoutRecord } from "db/dbAnivTimeouts";
import { sendMessage } from "lib/commandUtils";
import { redis } from "lib/redis";
import { timeout } from "lib/timeout";
import type User from "user";
import { playMSTTS } from "web/alerts/serverFunctions";

export const ANIVNAMES: anivBots[] = ["a_n_e_e_v", "a_n_i_v"];

type anivMessageStore = {
	[key: string]: string;
};

type IsAnivMessage = {
	isAnivMessage: true;
	message: string;
	anivbot: anivBots;
};

type isNotAnivMessage = {
	isAnivMessage: false;
};

export type anivBots = "a_n_i_v" | "a_n_e_e_v";

type anivMessageResult = IsAnivMessage | isNotAnivMessage;

async function isAnivMessage(message: string): Promise<anivMessageResult> {
	const data: anivMessageStore = await redis
		.get("anivmessages")
		.then((a) => (a === null ? {} : JSON.parse(a)));
	for (const clanker of ANIVNAMES) {
		const anivmessage = data[clanker];
		if (!anivmessage) continue;
		if (anivmessage === message)
			return { isAnivMessage: true, message, anivbot: clanker };
	}
	return { isAnivMessage: false };
}

export default async function handleMessage(
	msg: EventSubChannelChatMessageEvent,
	user: User,
) {
	if (ANIVNAMES.map((a) => a.toLowerCase()).includes(user.username)) {
		await playMSTTS({ text: msg.messageText });
		const data: anivMessageStore = await redis
			.get("anivmessages")
			.then((a) => (a === null ? {} : JSON.parse(a)));
		data[user.displayName] = msg.messageText;
		await redis.set("anivmessages", JSON.stringify(data));
	} else {
		const data = await isAnivMessage(msg.messageText);
		if (data.isAnivMessage) {
			if (Math.random() > 0.5) {
				// 1/2 chance to dodge aniv timeout
				await createAnivTimeoutRecord(msg.messageText, data.anivbot, user, 0);
				return;
			}

			const duration = Math.floor(Math.random() * 30) + 30; // minimum timeout of 30 sec, maximum of 60 sec

			await Promise.all([
				timeout(user, "copied an aniv message", 30),
				sendMessage(
					`${user.displayName} got timed out for copying an ${data.anivbot} message`,
				),
				createAnivTimeoutRecord(msg.messageText, data.anivbot, user, duration),
			]);
		}
	}
}
