import { getMoodleCourseCompletionStatus, getMoodleUserById } from "./moodle";
import { CronJob } from "cron";
import { prisma } from "@repo/db";
import { handleParticipantFinished } from "modules/event";

const syncMoodleIds = async () => {
	try {
		const user = await prisma.user.findMany({
			where: {
				moodleId: null,
			},
		});

		await Promise.all(
			user.map(async (u) => {
				const moodleUser = await getMoodleUserById(u.id.toString());
				const moodleId = moodleUser?.id.toString();
				if (u.moodleId === parseInt(moodleId)) return;
				await prisma.user.update({
					where: {
						id: u.id,
					},
					data: {
						moodleId: parseInt(moodleId),
					},
				});
			}),
		);
	} catch (error) {
		console.error(error);
	}
};

const updateParticipantMoodleResults = async () => {
	try {
		const participantsMoodlePending = await prisma.participant.findMany({
			where: {
				finisherMoodleCurseCompleted: false,
				Event: {
					finisherMoodleCourseId: {
						not: null,
					},
				},
			},
			include: {
				Event: true,
				User: true,
			},
		});
		await Promise.all(
			participantsMoodlePending.map(async (p) => {
				if (!p.User) return;
				if (!p.User.moodleId) return;

				const quizzResult = await getMoodleCourseCompletionStatus(
					p.User.moodleId.toString(),
					p.Event.finisherMoodleCourseId!,
				);

				if (quizzResult?.completionstatus?.completed === true) {
					await handleParticipantFinished(p.Event, p, p.User);

					return prisma.participant.update({
						where: {
							id: p.id,
						},
						data: {
							finisherMoodleCurseCompleted: true,
							statusLog: {
								push: {
									event: "Moodle-Kurs abgeschlossen",
									timestamp: new Date(),
									user: "system",
								},
							},
						},
					});
				}
			}),
		);
	} catch (error) {
		console.error("Error updating participant Moodle results:", error);
	}
};

CronJob.from({ cronTime: "0 * * * *", onTick: syncMoodleIds, start: true });
CronJob.from({
	cronTime: "*/1 * * * *",
	onTick: async () => {
		await updateParticipantMoodleResults();
	},
	start: true,
});
