import { DISCORD_ROLES, Event, getPublicUser, Participant, prisma } from "@repo/db";
import { Router } from "express";
import { changeMemberRoles, getMember } from "routes/member";

const router: Router = Router();

export const eventCompleted = (event: Event, participant?: Participant) => {
	if (!participant) return false;
	if (event.finisherMoodleCourseId && !participant.finisherMoodleCurseCompleted) return false;
	if (event.hasPresenceEvents && !participant.attended) return false;
	return true;
};

router.post("/set-standard-name", async (req, res) => {
	const { memberId, userId } = req.body;

	const user = await prisma.user.findUnique({
		where: {
			id: userId,
		},
	});
	console.log(`Setting standard name for user ${userId} (${user?.publicId}) to member ${memberId}`);
	if (!user) {
		res.status(404).json({ error: "User not found" });
		return;
	}
	const participant = await prisma.participant.findMany({
		where: {
			userId: user.id,
		},
		include: {
			Event: true,
		},
	});

	let eventRoles: string[] = [];

	participant.forEach(async (p) => {
		if (!p.Event.discordRoleId) return;
		if (eventCompleted(p.Event, p)) {
			await changeMemberRoles(memberId, [p.Event.discordRoleId], "remove");
		} else {
			await changeMemberRoles(memberId, [p.Event.discordRoleId], "add");
		}
	});

	const publicUser = getPublicUser(user);
	const member = await getMember(memberId);

	await member.setNickname(`${publicUser.fullName} (${user.publicId})`);
	const isPilot = user.permissions.includes("PILOT");
	const isDispatcher = user.permissions.includes("DISPO");

	await changeMemberRoles(memberId, [DISCORD_ROLES.PILOT], isPilot ? "add" : "remove");
	await changeMemberRoles(memberId, [DISCORD_ROLES.DISPATCHER], isDispatcher ? "add" : "remove");
});

export default router;
