import type { NetworkWithStreams, Stream } from "@/api/types";

export interface FlatStream extends Stream {
  networkId: string;
  networkName: string;
}

export function flattenStreams(
  networks: NetworkWithStreams[],
  selectedNetworkId: string | null,
): FlatStream[] {
  const filtered = selectedNetworkId
    ? networks.filter((n) => n.id === selectedNetworkId)
    : networks;

  const streams: FlatStream[] = filtered.flatMap((n) =>
    n.streams.map((s) => ({
      ...s,
      networkId: n.id,
      networkName: n.name,
    })),
  );

  return streams.sort((a, b) => {
    const aTime = getLatestParticleTime(a);
    const bTime = getLatestParticleTime(b);
    return bTime - aTime;
  });
}

function getLatestParticleTime(stream: Stream): number {
  if (stream.particles.length === 0) {
    return new Date(stream.updated_at).getTime() || 0;
  }
  const last = stream.particles[stream.particles.length - 1];
  return new Date(last.created_at).getTime();
}
