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

export const GET: RequestHandler = async ({ url, locals }) => {
  const accessToken = locals.session?.accessToken;
  if (!accessToken) {
    return json({ data: [] }, { status: 401 });
  }

  const search = url.searchParams.get("search") || "";
  const page = Number(url.searchParams.get("page")) || 1;
  const rpp = Number(url.searchParams.get("rpp")) || 15;

  try {
    const result = await optima.company.fetchMany(
      accessToken,
      page,
      search,
      rpp,
    );
    return json({ data: result?.data ?? [] });
  } catch (err) {
    console.error("[api/companies/search] Failed:", err);
    return json({ data: [] }, { status: 500 });
  }
};
