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 {
      companies: [],
      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") || "";

  try {
    const [result, permissions] = await Promise.all([
      optima.company.fetchMany(accessToken, page, search).catch((err) => {
        console.error(
          "Failed to fetch companies:",
          err?.response?.data ?? err?.message ?? err,
        );
        return {
          data: [],
          meta: {
            pagination: { totalPages: 1, currentPage: 1, totalRecords: 0 },
          },
        };
      }),
      checkPermissions(accessToken, ["companies.view"]),
    ]);

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