import { api } from '$lib/api';
import { getStoredClientSession, hasStoredClientSession } from '$lib/session';
import type { DashboardSummary } from '$lib/types';

const EMPTY_SUMMARY: DashboardSummary = {
  raw_materials: null,
  mixes: null,
  products: null,
  trend_seeds: { raw_material_cost_per_kg: [], mix_cost_per_kg: [], product_finished_delivered: [] }
};

// Streaming load: the route shell paints immediately and the dashboard fills
// in once `summary` resolves. This replaces the previous load that awaited
// five separate full collections (raw materials, mixes, all product cost
// breakdowns, scenarios, data-quality) before SvelteKit would render anything.
export function load({ fetch }) {
  if (!hasStoredClientSession()) {
    return { summary: Promise.resolve(EMPTY_SUMMARY) };
  }

  // Skip data fetching for sessions that lack any dashboard-eligible module
  // — the backend would just return nulls anyway.
  const session = getStoredClientSession();
  const permissions = session?.module_permissions ?? {};
  const hasAnyDashboardData =
    session?.role === 'admin' ||
    permissions.dashboard ||
    permissions.raw_materials ||
    permissions.mix_master ||
    permissions.products;
  if (!hasAnyDashboardData) {
    return { summary: Promise.resolve(EMPTY_SUMMARY) };
  }

  return {
    summary: api.dashboardSummary(fetch).catch(() => EMPTY_SUMMARY)
  };
}
