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

export const load: PageServerLoad = async ({ locals, params }) => {
  const accessToken = locals.session?.accessToken;
  if (!accessToken) {
    return {
      company: null,
      configurations: [],
      credentials: [],
      credentialTypes: [],
      unifiSites: [],
      accessToken: null,
      permissions: {} as PermissionMap,
    };
  }

  try {
    // Start the permission check separately so company.fetch can begin
    // as soon as permissions resolve, without waiting for the other fetches.
    const permissionsPromise = checkPermissions(accessToken, [
      "company.fetch.address",
      "company.fetch.contacts",
      "credential.secure_values.read",
      "unifi.site.wifi",
      "unifi.site.wifi.read.name",
      "unifi.site.wifi.update",
    ]);

    // Kick off all independent data fetches in parallel
    const configsPromise = optima.company.fetchConfigurations(
      accessToken,
      params.id,
    );
    const credentialsPromise = optima.credential
      .fetchByCompany(accessToken, params.id)
      .catch(() => ({ data: [] }));
    const credentialTypesPromise = optima.credentialType
      .fetchMany(accessToken)
      .catch(() => ({ data: [] }));
    const unifiSitesPromise = optima.unifi
      .fetchCompanySites(accessToken, params.id)
      .catch(() => ({ data: [] }));

    // company.fetch only depends on permissions — start it as soon as
    // permissions resolve, don't wait for the other fetches
    const companyPromise = permissionsPromise.then((permissions) =>
      optima.company.fetch(accessToken, params.id, {
        includeAddress: permissions["company.fetch.address"] === true,
        includePrimaryContact: true,
        includeAllContacts: permissions["company.fetch.contacts"] === true,
        includeAllAddresses: permissions["company.fetch.address"] === true,
      }),
    );

    // Now await everything together
    const [
      permissions,
      configsResult,
      credentialsResult,
      credentialTypesResult,
      unifiSitesResult,
      companyResult,
    ] = await Promise.all([
      permissionsPromise,
      configsPromise,
      credentialsPromise,
      credentialTypesPromise,
      unifiSitesPromise,
      companyPromise,
    ]);

    return {
      company: companyResult?.data ?? null,
      configurations: configsResult?.data ?? [],
      credentials: credentialsResult?.data ?? [],
      credentialTypes: credentialTypesResult?.data ?? [],
      unifiSites: unifiSitesResult?.data ?? [],
      accessToken,
      permissions,
    };
  } catch (err) {
    handleApiError(err);
  }
};
