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

export async function load({ fetch }) {
  if (!hasStoredClientSession()) {
    return { items: [], inputs: null };
  }

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

  try {
    const canRead = hasModuleAccess(session, 'products') || session?.role === 'internal';
    if (!canRead) {
      return { items: [], inputs: null };
    }

    const [items, inputs] = await Promise.all([
      api.productCostingItems(fetch),
      api.productCostingInputs(fetch)
    ]);
    return { items, inputs };
  } catch {
    return { items: [], inputs: null };
  }
}
