import { Event, Participant, prisma, User } from "@repo/db";
import { removeRolesFromMember } from "modules/discord";
import { sendCourseCompletedEmail } from "modules/mail";

export const handleParticipantFinished = async (
	event: Event,
	participant: Participant,
	user: User,
) => {
	const discordAccount = await prisma.discordAccount.findFirst({
		where: {
			userId: user.id,
		},
	});

	const badgedToAdd = event.finishedBadges.filter((badge) => {
		return !user.badges.includes(badge);
	});
	const permissionsToAdd = event.finishedPermissions.filter((permission) => {
		return !user.permissions.includes(permission);
	});

	await prisma.user.update({
		where: {
			id: user.id,
		},
		data: {
			badges: {
				push: badgedToAdd,
			},
			permissions: {
				push: permissionsToAdd,
			},
		},
	});

	if (event.discordRoleId && discordAccount) {
		await removeRolesFromMember(discordAccount.discordId, [event.discordRoleId]);
	}
	await sendCourseCompletedEmail(user.email, user, event);

	await prisma.participant.update({
		where: {
			id: participant.id,
		},
		data: {
			completetionWorkflowFinished: true,
			statusLog: {
				push: {
					event: "Berechtigungen und Badges vergeben",
					timestamp: new Date(),
					user: "system",
				},
			},
		},
	});
};
