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

export async function load({ fetch }) {
  if (!hasStoredClientSession()) {
    return { catalogue: [], orders: [], canOrder: false };
  }

  const session = getStoredClientSession();
  // Internal staff manage orders rather than place them — send them to the
  // management console.
  if (canManageOrdering(session)) {
    throw redirect(307, '/ordering/manage');
  }
  if (!canOpenCustomerOrdering(session)) {
    throw redirect(307, getWorkspaceHomeHref(session));
  }

  try {
    const [catalogue, orders] = await Promise.all([api.ordering.catalogue(undefined, fetch), api.ordering.orders(undefined, fetch)]);
    return { catalogue, orders, canOrder: true };
  } catch {
    return { catalogue: [], orders: [], canOrder: true };
  }
}
