import { optima } from "$lib";
import { handleApiError } from "$lib/optima-api/errorHandler";
import { checkPermissions } from "$lib/permissions";
import type { PageServerLoad } from "./$types";

export const load: PageServerLoad = async ({ locals, url }) => {
  const accessToken = locals.session?.accessToken;
  if (!accessToken) {
    return {
      items: [],
      totalPages: 1,
      currentPage: 1,
      totalRecords: 0,
      search: "",
      permissions: {},
    };
  }

  const page = Math.max(1, Number(url.searchParams.get("page")) || 1);
  const search = url.searchParams.get("search") || "";
  const includeInactive = url.searchParams.get("includeInactive") === "true";

  try {
    const [result, permissions] = await Promise.all([
      optima.procurement
        .fetchMany(accessToken, page, { search, includeInactive }, 30)
        .catch((err) => {
          console.error(
            "Failed to fetch catalog items:",
            err?.response?.data ?? err?.message ?? err,
          );
          return {
            data: [],
            meta: {
              pagination: { totalPages: 1, currentPage: 1, totalRecords: 0 },
            },
          };
        }),
      checkPermissions(accessToken, [
        "procurement.catalog.fetch.many",
        "procurement.catalog.inventory.refresh",
        "procurement.catalog.fetch",
        "procurement.catalog.link",
      ]),
    ]);

    return {
      items: result?.data ?? [],
      totalPages: result?.meta?.pagination?.totalPages ?? 1,
      currentPage: result?.meta?.pagination?.currentPage ?? page,
      totalRecords:
        result?.meta?.pagination?.totalRecords ?? result?.data?.length ?? 0,
      search,
      includeInactive,
      permissions,
    };
  } catch (err) {
    handleApiError(err);
  }
};
