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

export async function load({ params, fetch }) {
  if (!hasStoredClientSession()) {
    return {
      session: null,
      options: { clients: [], products: [] }
    };
  }

  const session = getStoredClientSession();
  const canView = canOpenMixCalculator(session);
  const canEdit = canCreateMixSession(session);

  if (!canView) {
    throw redirect(307, getWorkspaceHomeHref(session));
  }

  try {
    const [savedSession, options] = await Promise.all([
      api.mixCalculatorSession(Number(params.id), fetch),
      canEdit || session?.role === 'internal' ? api.mixCalculatorOptions(fetch) : Promise.resolve({ clients: [], products: [] })
    ]);

    return {
      session: savedSession,
      options
    };
  } catch {
    return {
      session: null,
      options: { clients: [], products: [] }
    };
  }
}
