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

export const GET = async (req: NextRequest) => {
	try {
		const session = await getServerSession();
		if (!session?.user) {
			return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
		}

		const { searchParams } = req.nextUrl;
		const filter = JSON.parse(searchParams.get("filter") || "{}");

		const bookings = await prisma.booking.findMany({
			where: filter,
			include: {
				User: true,
				Station: {
					select: {
						id: true,
						bosCallsign: true,
						bosCallsignShort: true,
					},
				},
			},
			orderBy: {
				startTime: "asc",
			},
		});

		return NextResponse.json(
			bookings.map((b) => ({
				...b,
				User: b.User ? getPublicUser(b.User) : null,
			})),
		);
	} catch (error) {
		console.error("Error fetching bookings:", error);
		return NextResponse.json({ error: "Internal server error" }, { status: 500 });
	}
};
