import { getUserRecord } from "db/dbUser";
import { api, eventSub } from "index";
import { changeItemCount } from "items";
import { sendMessage } from "lib/commandUtils";
import logger from "lib/logger";
import { redis } from "lib/redis";
import { streamerId } from "main";
import User from "user";

eventSub.onChannelRaidTo(streamerId, async (msg) => {
	if (await redis.exists(`user:${msg.raidingBroadcasterId}:recentraid`)) {
		await sendMessage(
			`Another raid from ${msg.raidedBroadcasterDisplayName}??? SMH`,
		);
		return;
	}
	await redis.set(`user:${msg.raidingBroadcasterId}:recentraid`, "1");
	await redis.expire(`user:${msg.raidingBroadcasterId}:recentraid`, 60 * 30); // raid cooldown is 30 minutes
	await sendMessage(
		`Ty for raiding ${msg.raidingBroadcasterDisplayName}. You get 3 pieces of TNT. Enjoy!`,
	);
	try {
		await api.chat.shoutoutUser(streamerId, msg.raidingBroadcasterId);
	} catch (_e) {
		logger.warn(
			`Failed to give automatic shoutout to ${msg.raidingBroadcasterDisplayName}`,
		);
	}
	const raider = await User.initUsername(msg.raidingBroadcasterName);
	const result = await changeItemCount(
		raider!,
		await getUserRecord(raider!),
		"tnt",
		3,
	);
	if (!result) await sendMessage("oopsies, no tnt for you!");
});
