import type { cheers } from "cheers";
import db from "db/connection";
import { timeouts } from "db/schema";
import { and, between, eq, type SQL } from "drizzle-orm";
import type { items } from "items";
import type User from "user";

export async function createTimeoutRecord(
	user: User,
	target: User,
	item: items | cheers,
): Promise<void> {
	await db.insert(timeouts).values({
		user: parseInt(user.id, 10),
		target: parseInt(target.id, 10),
		item,
	});
}

export async function getTimeoutsAsUser(user: User, monthData?: string) {
	let condition: SQL<unknown> | undefined = eq(
		timeouts.user,
		parseInt(user.id, 10),
	);
	if (monthData) {
		const begin = Date.parse(monthData);
		const end = new Date(begin).setMonth(new Date(begin).getMonth() + 1);
		condition = and(
			condition,
			between(timeouts.created, new Date(begin), new Date(end)),
		);
	}
	const data = await db.select().from(timeouts).where(condition);
	return data;
}

export async function getTimeoutsAsTarget(user: User, monthData?: string) {
	let condition: SQL<unknown> | undefined = eq(
		timeouts.target,
		parseInt(user.id, 10),
	);
	if (monthData) {
		const begin = Date.parse(monthData);
		const end = new Date(begin).setMonth(new Date(begin).getMonth() + 1);
		condition = and(
			condition,
			between(timeouts.created, new Date(begin), new Date(end)),
		);
	}
	const data = await db.select().from(timeouts).where(condition);
	return data;
}
