import type { StoredPack } from "@/lib/offline/db"; import type { HiveSetupView, HiveSystemDto } from "./types"; // What the offline packs say about hives (spec 10). Both fields are optional: // a pack from before the hive card says nothing, and "nothing" is not "no hive". function newestFirst(packs: readonly StoredPack[]): StoredPack[] { return [...packs].sort((a, b) => b.savedAt.localeCompare(a.savedAt)); } /** * The colony's hive per its newest pack. `null`: no pack lists the colony or * the pack predates hives, so it cannot tell. `{ setup: null }`: the pack * knows the colony and the colony has no hive yet. */ export function hiveFromPacks( packs: readonly StoredPack[], colonyId: string, ): { setup: HiveSetupView | null } | null { const holding = newestFirst(packs).find((stored) => stored.pack.colonies.some((colony) => colony.id === colonyId), ); if (!holding?.pack.hives) return null; return { setup: holding.pack.hives[colonyId] ?? null }; } /** The hive systems of the newest pack that carries them; null when none does. */ export function hiveCatalogFromPacks(packs: readonly StoredPack[]): HiveSystemDto[] | null { return newestFirst(packs).find((stored) => stored.pack.hiveCatalog)?.pack.hiveCatalog ?? null; }