import { redirect } from '@sveltejs/kit';
import { api } from '$lib/api';
import { getStoredClientSession, hasStoredClientSession } from '$lib/session';
import { canOpenDashboard, getWorkspaceHomeHref, isCustomerPortalSession } from '$lib/workspace-access';
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: [] },
  operations: null
};

// 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) };
  }

  const session = getStoredClientSession();

  // B2B ordering customers must never land on (or flash) the internal
  // dashboard — even if their account happens to carry the dashboard module.
  // Send them straight to their catalogue before any dashboard data loads.
  if (isCustomerPortalSession(session)) {
    throw redirect(307, '/ordering');
  }

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

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