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({
		include: {
			appointments: {
				where: {
					appointmentDate: {
						gte: new Date(),
					},
				},
			},
			participants: {
				where: {
					userId: user.id,
				},
			},
		},
	});
	const userAppointments = await prisma.eventAppointment.findMany({
		where: {
			Participants: {
				some: {
					userId: user.id,
				},
			},
		},
	});

	const appointments = await prisma.eventAppointment.findMany({
		where: {
			appointmentDate: {
				gte: new Date(),
			},
		},
		include: {
			Participants: {
				where: {
					userId: user.id,
				},
			},
			_count: {
				select: {
					Participants: true,
				},
			},
		},
	});

	const filteredEvents = events.filter((event) => {
		if (eventCompleted(event, event.participants[0])) 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={appointments}
							selectedAppointments={userAppointments}
							user={user}
							event={event}
							key={event.id}
						/>
					);
				})}
			</div>
		</div>
	);
};

export default page;
