import { redirect } from '@sveltejs/kit';
import { api } from '$lib/api';
import { getStoredClientSession, hasModuleAccess, hasStoredClientSession } from '$lib/session';
import { canOpenMixCalculator, getWorkspaceHomeHref } from '$lib/workspace-access';

export async function load({ params, fetch }) {
  if (!hasStoredClientSession()) {
    return {
      session: null
    };
  }

  const session = getStoredClientSession();

  if (!canOpenMixCalculator(session)) {
    throw redirect(307, getWorkspaceHomeHref(session));
  }

  try {
    return {
      session: await api.mixCalculatorSession(Number(params.id), fetch)
    };
  } catch {
    return {
      session: null
    };
  }
}
