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

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

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

  try {
    return {
      options: hasModuleAccess(session, 'mix_calculator', 'edit') || session?.role === 'internal'
        ? await api.mixCalculatorOptions(fetch)
        : { clients: [], products: [] }
    };
  } catch {
    return {
      options: { clients: [], products: [] }
    };
  }
}
