import { NextResponse } from "next/server";
import { api } from "../../../../convex/_generated/api";
import { q } from "@/lib/convex-server";
import { getCurrentUser } from "@/lib/auth";

/** Global search (command palette) — references, customers, reservations, apartments, workers, contracts, tickets. */
export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const term = new URL(req.url).searchParams.get("q")?.trim() ?? "";
  if (term.length < 2) return NextResponse.json({ hits: [] });
  const hits = await q(api.search.global, { q: term });
  return NextResponse.json({ hits }, { headers: { "Cache-Control": "private, no-store" } });
}
