import { db } from "~/db/sql";
import * as Seasons from "~/features/mmr/core/Seasons";
import { dateToDatabaseTimestamp } from "~/utils/dates";
import invariant from "~/utils/invariant";
import { logger } from "~/utils/logger";

const discordId = process.argv[2]?.trim();

invariant(discordId, "discord id is required (argument 1)");

async function main() {
	const currentSeason = Seasons.current();
	if (!currentSeason) {
		logger.info("No current season found");
		return;
	}

	const user = await db
		.selectFrom("User")
		.select(["User.id"])
		.where("User.discordId", "=", discordId)
		.executeTakeFirstOrThrow();

	const playedMaps = await db
		.selectFrom("GroupMember")
		.innerJoin("Group", "Group.id", "GroupMember.groupId")
		.innerJoin("GroupMatch", (join) =>
			join.on((eb) =>
				eb.or([
					eb("GroupMatch.alphaGroupId", "=", eb.ref("Group.id")),
					eb("GroupMatch.bravoGroupId", "=", eb.ref("Group.id")),
				]),
			),
		)
		.innerJoin("GroupMatchMap", "GroupMatchMap.matchId", "GroupMatch.id")
		.select(["GroupMatchMap.matchId", "GroupMatchMap.index"])
		.where(
			"GroupMatch.createdAt",
			">",
			dateToDatabaseTimestamp(currentSeason.starts),
		)
		.where(
			"GroupMatch.createdAt",
			"<",
			dateToDatabaseTimestamp(currentSeason.ends),
		)
		.where("GroupMember.userId", "=", user.id)
		.where("GroupMatchMap.winnerGroupId", "is not", null)
		.execute();

	if (playedMaps.length === 0) {
		logger.info(`No reported weapons to delete for user ${discordId}`);
		return;
	}

	await db
		.deleteFrom("ReportedWeapon")
		.where("userId", "=", user.id)
		.where((eb) =>
			eb.or(
				playedMaps.map((m) =>
					eb.and([
						eb("ReportedWeapon.groupMatchId", "=", m.matchId),
						eb("ReportedWeapon.mapIndex", "=", m.index),
					]),
				),
			),
		)
		.execute();

	logger.info(
		`Deleted reported weapons across ${playedMaps.length} maps for user ${discordId}`,
	);
}

void main();
