import { optima } from "$lib";
import { handleApiError } from "$lib/optima-api/errorHandler";
import { checkPermissions, type PermissionMap } from "$lib/permissions";
import { redirect } from "@sveltejs/kit";
import type { LayoutServerLoad } from "./$types";

export const load: LayoutServerLoad = async ({ locals, parent }) => {
  const accessToken = locals.session?.accessToken;
  if (!accessToken) {
    throw redirect(303, "/login");
  }

  try {
    // Grab the root layout data to reuse the admin-view permission it already checked
    const parentData = await parent();

    // If the root layout already determined we can't view admin, redirect immediately
    if (parentData?.canViewAdmin === false) {
      throw redirect(303, "/");
    }

    // Fetch sub-tab permissions and user info in parallel
    const [permissions, userInfo] = await Promise.all([
      checkPermissions(accessToken, [
        "admin.users.view",
        "admin.roles.view",
        "admin.credential-types.view",
        "ui.navigation.reports.view",
      ]),
      optima.user.fetchInfo(accessToken),
    ]);

    return {
      user: userInfo?.data ?? null,
      permissions: {
        "ui.navigation.admin.view": true, // Already verified via parent
        ...permissions,
      },
    };
  } catch (err) {
    // Re-throw redirects so SvelteKit handles them
    if (err && typeof err === "object" && "status" in err) {
      throw err;
    }
    handleApiError(err);
  }
};
