import { NextResponse } from "next/server";
import { getToken } from "@/lib/session";

const API_URL = process.env.NEXT_PUBLIC_API_URL;

/**
 * Thin proxy to Laravel GET /petugas/participants/search. Unlike the other
 * authenticated GETs (fetched directly from Server Components via
 * lib/api/server.ts), this one backs a live search box that needs to run
 * from a Client Component — so, like the mutation routes, it proxies through
 * here to attach the httpOnly-cookie Bearer token server-side.
 */
export async function GET(request: Request) {
  const token = await getToken();

  if (!token) {
    return NextResponse.json({ message: "You must log in first." }, { status: 401 });
  }

  const { search } = new URL(request.url);

  const apiRes = await fetch(`${API_URL}/petugas/participants/search${search}`, {
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`,
    },
    cache: "no-store",
  });

  const data = await apiRes.json();

  return NextResponse.json(data, { status: apiRes.status });
}
