import { optima } from "$lib";
import type { LayoutServerLoad } from "./$types";

export const load: LayoutServerLoad = async ({ locals }) => {
  const accessToken = locals.session?.accessToken ?? null;

  // Only check permissions if the user is authenticated
  if (!accessToken) {
    return { canViewAdmin: false, user: null };
  }

  let canViewAdmin = false;
  let user = null;
  try {
    const userInfo = await optima.user.fetchInfo(accessToken);
    user = userInfo.data ?? null;

    const permResult = await optima.user.checkPermissions(accessToken, [
      "ui.navigation.admin.view",
    ]);
    canViewAdmin = permResult?.data?.results?.[0]?.hasPermission === true;
  } catch (err) {
    console.error("Admin permission check or user fetch failed:", err);
    canViewAdmin = false;
    user = null;
  }

  return { canViewAdmin, user };
};
