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

export async function GET(req: NextRequest): Promise<NextResponse> {
	const { searchParams } = new URL(req.url);
	const id = searchParams.get("id");
	const filter = searchParams.get("filter");
	const include = searchParams.get("include");
	const orderBy = searchParams.get("orderBy");

	const filterParsed = JSON.parse(filter || "{}");
	const includeParsed = JSON.parse(include || "{}");
	const orderByParsed = JSON.parse(orderBy || "{}");

	try {
		const data = await prisma.mission.findMany({
			where: {
				id: id ? Number(id) : undefined,
				...filterParsed,
			},
			include: {
				...includeParsed,
			},
			orderBy: {
				...orderByParsed,
			},
		});

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