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

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

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

  // Default view shows the last 30 days; "Find past entries" surfaces older ones.
  const recentFrom = new Date();
  recentFrom.setDate(recentFrom.getDate() - 30);
  const dateFrom = recentFrom.toISOString().slice(0, 10);

  // The overview cards are computed in the browser: the hero cards (today /
  // this week / 4-week average) plus the customer-mix cards whose rolling range
  // the operator can switch up to 12 weeks. Pull that widest window once so
  // changing range is a pure re-filter with no extra request.
  const statsFrom = new Date();
  statsFrom.setDate(statsFrom.getDate() - 84);
  const statsDateFrom = statsFrom.toISOString().slice(0, 10);

  try {
    const [entries, statsEntries, products] = await Promise.all([
      api.throughputEntries({ date_from: dateFrom, limit: 200 }, fetch),
      api.throughputEntries({ date_from: statsDateFrom, limit: 1000 }, fetch),
      api.throughputProducts(fetch)
    ]);
    return { entries, statsEntries, products };
  } catch {
    return { entries: [], statsEntries: [], products: [] };
  }
}
