import db from "db/connection";
import { anivTimeouts } from "db/schema";
import { and, count, eq } from "drizzle-orm";
import type { anivBots } from "lib/handleAnivMessage";
import type User from "user";

/** To create a dodge record, set the duration to 0 */
export async function createAnivTimeoutRecord(
	message: string,
	anivBot: anivBots,
	user: User,
	duration: number,
) {
	await db.insert(anivTimeouts).values({
		message,
		anivBot,
		user: parseInt(user.id, 10),
		duration,
		timeout: duration !== 0,
	});
}

export async function getAnivTimeouts(user: User) {
	let [dodge, dead] = await Promise.all([
		db
			.select({
				dodge: count(),
			})
			.from(anivTimeouts)
			.where(
				and(
					eq(anivTimeouts.user, parseInt(user.id, 10)),
					eq(anivTimeouts.timeout, false),
				),
			)
			.then((a) => a[0]?.dodge),
		db
			.select({
				dead: count(),
			})
			.from(anivTimeouts)
			.where(
				and(
					eq(anivTimeouts.user, parseInt(user.id, 10)),
					eq(anivTimeouts.timeout, true),
				),
			)
			.then((a) => a[0]?.dead),
	]);

	if (!dodge) dodge = 0;
	if (!dead) dead = 0;

	return { dodge, dead };
}
