import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@repo/db";
import { verify } from "jsonwebtoken";
import { getMoodleUserById } from "../../../helper/moodle";
import { inscribeToMoodleCourse } from "../../(app)/events/actions";

export const GET = async (req: NextRequest) => {
	// This route is only used by Moodle and DEsktop-client, so NextAuth is not used here
	const authHeader = req.headers.get("Authorization");
	const token = authHeader?.split(" ")[1];
	if (!authHeader || !token) {
		return NextResponse.json({ error: "Not logged in" }, { status: 401 });
	}
	const decoded = await verify(token, process.env.AUTH_HUB_SECRET as string);

	if (typeof decoded === "string")
		return NextResponse.json({ error: "Invalid token" }, { status: 401 });

	const user = await prisma.user.findUnique({
		where: {
			id: decoded.id,
		},
	});

	if (!user) return NextResponse.json({ error: "User not found" }, { status: 404 });
	setTimeout(async () => {
		const moodleUser = await getMoodleUserById(user.id);
		await prisma.user.update({
			where: {
				id: user.id,
			},
			data: {
				moodleId: moodleUser?.id,
			},
		});

		const participatingEvents = await prisma.participant.findMany({
			where: {
				userId: user.id,
				Event: {
					finisherMoodleCourseId: {
						not: null,
					},
				},
			},
			include: {
				Event: true,
			},
		});
		participatingEvents.forEach(async (p) => {
			await inscribeToMoodleCourse(p.Event.finisherMoodleCourseId!, moodleUser?.id);
		});
	}, 1000);

	return NextResponse.json({
		...user,
		moodleLastname: `${user?.lastname.split("")[0]}. - ${user?.publicId}`,
	});
};
