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

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

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

  try {
    return {
      rawMaterials:
        (hasModuleAccess(session, 'mix_master') && hasModuleAccess(session, 'raw_materials')) || session?.role === 'internal'
          ? await api.rawMaterials(fetch)
          : []
    };
  } catch {
    return {
      rawMaterials: []
    };
  }
}
