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

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

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

  try {
    const [rawMaterials, mixes, products, productCosts] = await Promise.all([
      hasModuleAccess(session, 'raw_materials') || session?.role === 'internal' ? api.rawMaterials(fetch) : Promise.resolve([]),
      hasModuleAccess(session, 'mix_master') || session?.role === 'internal' ? api.mixes(fetch) : Promise.resolve([]),
      hasModuleAccess(session, 'products') || session?.role === 'internal' ? api.products(fetch) : Promise.resolve([]),
      hasModuleAccess(session, 'products') || session?.role === 'internal' ? api.productCosts(fetch) : Promise.resolve([])
    ]);

    return {
      rawMaterials,
      mixes,
      products,
      productCosts
    };
  } catch {
    return {
      rawMaterials: [],
      mixes: [],
      products: [],
      productCosts: []
    };
  }
}
