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,
				ghostMode: false, // Ensure we only get non-ghost mode connections
				...filter, // Ensure filter is parsed correctly
			},
			include: {
				user: true,
			},
		});

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