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

export async function load({ fetch }) {
  // Single-page mode (session history disabled): this route IS the calculator.
  if (!featureFlags.mixCalculatorSessionHistory) {
    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: [] } };
    }
  }

  // History mode: list saved sessions.
  if (!hasStoredClientSession()) {
    return { sessions: [] };
  }

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

  try {
    return {
      sessions:
        hasModuleAccess(session, 'mix_calculator') || session?.role === 'internal'
          ? await api.mixCalculatorSessions(fetch)
          : []
    };
  } catch {
    return { sessions: [] };
  }
}
