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

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

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

  try {
    const [products, productCosts] = await Promise.all([
      hasModuleAccess(session, 'products') || session?.role === 'internal' ? api.products(fetch) : Promise.resolve([]),
      hasModuleAccess(session, 'products') || session?.role === 'internal' ? api.productCosts(fetch) : Promise.resolve([])
    ]);
    return {
      products,
      productCosts
    };
  } catch {
    return {
      products: [],
      productCosts: []
    };
  }
}
