import { optima } from "$lib";
import { json, error } from "@sveltejs/kit";
import type { RequestHandler } from "./$types";

/** GET /procurement/catalog/search?q=<query> — search catalog items for linking */
export const GET: RequestHandler = async ({ url, locals }) => {
  const accessToken = locals.session?.accessToken;
  if (!accessToken) throw error(401, "Unauthorized");

  const query = url.searchParams.get("q") || "";
  if (!query.trim()) return json({ data: [] });

  try {
    const result = await optima.procurement.fetchMany(
      accessToken,
      1,
      { search: query, includeInactive: true },
      20,
    );
    return json({ data: result?.data ?? [] });
  } catch (err: unknown) {
    console.error("Failed to search catalog items:", err);
    const status =
      err && typeof err === "object" && "status" in err
        ? (err as { status: number }).status
        : 500;
    throw error(status, "Failed to search catalog items");
  }
};
