import { prisma, Prisma } from "@repo/db";
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest): Promise<NextResponse> {
	try {
		const connectedAircraftId = request.nextUrl.searchParams.get("connectedAircraftId");

		const aircraft = await prisma.connectedAircraft.findUnique({
			where: {
				id: connectedAircraftId ? parseInt(connectedAircraftId) : undefined,
			},
		});
		if (!aircraft) return NextResponse.json({ error: "Aircraft not found" }, { status: 404 });

		const positionLog = await prisma.positionLog.findMany({
			where: {
				id: {
					in: aircraft.positionLogIds,
				},
				timestamp: {
					gte: new Date(Date.now() - 2 * 60 * 60 * 1000), // Last 2 hours
				},
			},
		});

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