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

export async function GET(request: Request): Promise<NextResponse> {
	try {
		const filter = JSON.parse(
			new URL(request.url).searchParams.get("filter") || "{}",
		) as Prisma.ConnectedDispatcherWhereInput;

		const connectedDispatcher = await prisma.connectedDispatcher.findMany({
			where: {
				logoutTime: null,
				...filter, // Ensure filter is parsed correctly
			},
			include: {
				user: true,
			},
		});

		return NextResponse.json(
			connectedDispatcher.map((d) => {
				return {
					...d,
					user: undefined,
					publicUser: getPublicUser(d.user),
				};
			}),
			{
				status: 200,
			},
		);
	} catch (error) {
		console.error(error);
		return NextResponse.json({ error: "Failed to fetch Dispatchers" }, { status: 500 });
	}
}
