import { getServerSession } from "../../api/auth/[...nextauth]/auth";
import { prisma } from "@repo/db";
import { KursItem } from "../events/_components/item";
import { RocketIcon } from "lucide-react";
import { eventCompleted } from "../../../helper/events";

const page = async () => {
	const session = await getServerSession();

	if (!session) return null;

	const user = session.user;

	if (!user) return null;

	const events = await prisma.event.findMany({
		where: {
			type: "OBLIGATED_COURSE",
		},
		include: {
			participants: {
				where: {
					userId: user.id,
				},
			},
			appointments: {
				include: {
					Participants: {
						where: {
							appointmentCancelled: false,
						},
					},
				},
			},
		},
	});

	const filteredEvents = events.filter((event) => {
		const userParticipant = event.participants.find(
			(participant) => participant.userId === user.id,
		);
		if (eventCompleted(event, userParticipant)) return false;
		if (event.type === "OBLIGATED_COURSE" && !eventCompleted(event, event.participants[0]))
			return true;
		return false;
	});

	if (!filteredEvents.length) return null;
	return (
		<div>
			<div className="col-span-full">
				<p className="text-xl font-semibold text-left flex items-center gap-2 mb-2 mt-5">
					<RocketIcon className="w-4 h-4" /> Laufende Events & Kurse
				</p>
			</div>
			<div className="grid grid-cols-6 gap-4">
				{filteredEvents.map((event) => {
					return (
						<KursItem
							appointments={event.appointments}
							selectedAppointments={event.appointments.filter((a) =>
								a.Participants.find((p) => p.userId == user.id),
							)}
							user={user}
							event={event}
							key={event.id}
						/>
					);
				})}
			</div>
		</div>
	);
};

export default page;
