import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { LegalDirectoryFiltersSchema } from "@/lib/legal/types";
import { listLegalDirectory } from "@/lib/legal/server";

export async function GET(request: Request) {
  const user = await requireAdminApiUser();

  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { searchParams } = new URL(request.url);
  const parsed = LegalDirectoryFiltersSchema.safeParse({
    jurisdictionLevel: searchParams.get("jurisdictionLevel") ?? undefined,
    stateCode: searchParams.get("stateCode") ?? undefined,
    q: searchParams.get("q") ?? undefined,
  });

  if (!parsed.success) {
    return NextResponse.json({ error: "Filtros invalidos." }, { status: 400 });
  }

  const entities = await listLegalDirectory(parsed.data);
  return NextResponse.json({ ok: true, entities });
}
