import { Prisma, prisma } from "@repo/db";
import { getServerSession } from "api/auth/[...nextauth]/auth";
import { NextResponse } from "next/server";

export async function GET(request: Request): Promise<NextResponse> {
	try {
		const session = await getServerSession();

		if (!session) {
			return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
		}

		const filter = JSON.parse(
			new URL(request.url).searchParams.get("filter") || "{}",
		) as Prisma.EventWhereInput;

		const connectedAircraft = await prisma.event.findMany({
			where: {
				...filter, // Ensure filter is parsed correctly
			},
			include: {
				Participants: {
					where: {
						userId: session.user.id,
					},
				},
				Appointments: {
					include: {
						Participants: {
							where: {
								appointmentCancelled: false,
							},
						},
					},
				},
			},
		});

		return NextResponse.json(connectedAircraft, {
			status: 200,
		});
	} catch (error) {
		console.error(error);
		return NextResponse.json({ error: "Failed to fetch Aircrafts" }, { status: 500 });
	}
}
