import { api } from '$lib/api';
import { getStoredClientSession, hasModuleAccess, hasStoredClientSession } from '$lib/session';

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

  const session = getStoredClientSession();
  const canView = hasModuleAccess(session, 'mix_calculator');
  const canEdit = hasModuleAccess(session, 'mix_calculator', 'edit');

  if (!canView) {
    return {
      session: null,
      options: { clients: [], products: [] }
    };
  }

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

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