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

export async function load({ fetch }) {
  if (!hasStoredClientSession()) {
    return {
      scenarios: []
    };
  }

  const session = getStoredClientSession();
  if (!canOpenScenarios(session)) {
    throw redirect(307, getWorkspaceHomeHref(session));
  }

  try {
    return {
      scenarios: hasModuleAccess(session, 'scenarios') ? await api.scenarios(fetch) : []
    };
  } catch {
    return {
      scenarios: []
    };
  }
}
