// Fleet weekly trend: total monthly cost + potential savings, one point per
// run, aggregated client-side from /api/v1/runs. Only successful runs have
// an honest fleet total — a partial run's summary carries its succeeded
// regions only, so plotting their sum would read as a fleet-wide dip. Those
// points carry nulls instead, which recharts renders as a line gap.

import type { RunSummaryFile } from "@/lib/api-types";
import { runCostOf, runSavingsOf } from "@/lib/run-metrics";
import { utc8DateOf } from "@/lib/time";
import { Empty } from "@/components/ui/Empty";
import { CostSavingsTrendChart } from "@/components/CostSavingsTrendChart";

export function fleetTrendPoints(runs: RunSummaryFile[]): Array<{
  date: string;
  cost: number | null;
  savings: number | null;
}> {
  return [...runs]
    .reverse()
    .map((r) => ({
      date: utc8DateOf(r.finishedAt),
      cost: r.status === "success" ? runCostOf(r) : null,
      savings: r.status === "success" ? runSavingsOf(r) : null,
    }));
}

export function FleetTrendChart({ runs }: { runs: RunSummaryFile[] }) {
  const points = fleetTrendPoints(runs);
  if (points.length < 2 || points.every((p) => p.cost === null)) {
    return <Empty>Need at least two runs with data for a trend.</Empty>;
  }
  return <CostSavingsTrendChart data={points} />;
}
