import type { TreeCategory, TreeTech } from "./types"; /** * Project a `technologies` REST/local API doc (depth 0: relationships are * plain ids) into the lightweight TreeTech shape used by the tree. */ export function mapTechDoc(doc: Record): TreeTech { const requirements = doc.requirements as { prerequisiteTechnologies?: unknown[] } | null; const rows = Array.isArray(requirements?.prerequisiteTechnologies) ? (requirements!.prerequisiteTechnologies as Record[]) : []; const prereqAnd: number[] = []; const prereqOr: number[] = []; for (const row of rows) { const requiresAnd = row?.requiresAnd as { technology?: unknown[] } | undefined; const requiresOr = row?.requiresOr as { technology?: unknown[] } | undefined; for (const t of requiresAnd?.technology ?? []) { if (typeof t === "number") prereqAnd.push(t); } for (const t of requiresOr?.technology ?? []) { if (typeof t === "number") prereqOr.push(t); } } const researchCosts = doc.researchCosts as { resources?: unknown[] } | null; const costRows = Array.isArray(researchCosts?.resources) ? (researchCosts!.resources as Record[]) : []; const resourceCosts = costRows .map((row) => ({ resource: row?.resource as number, amount: typeof row?.amount === "number" ? row.amount : 0, })) .filter((row) => typeof row.resource === "number"); const manualPosition = doc.treePosition as { x?: unknown; y?: unknown } | null | undefined; const treePosition = manualPosition && typeof manualPosition.x === "number" && typeof manualPosition.y === "number" && Number.isFinite(manualPosition.x) && Number.isFinite(manualPosition.y) ? { x: manualPosition.x, y: manualPosition.y } : null; return { id: doc.id as number, name: String(doc.name ?? ""), type: doc.type === "asset" ? "asset" : "upgrade", approvalStatus: String(doc.approvalStatus ?? "in_progress"), summary: String(doc.summary ?? ""), categoryId: typeof doc.category === "number" ? doc.category : null, prereqAnd: [...new Set(prereqAnd)], prereqOr: [...new Set(prereqOr)].filter((id) => !prereqAnd.includes(id)), resourceCosts, treePosition, updatedAt: String(doc.updatedAt ?? ""), }; } /** Project a `tech-categories` doc into the TreeCategory shape. */ export function mapCategoryDoc(doc: Record): TreeCategory { return { id: doc.id as number, name: String(doc.name ?? ""), position: typeof doc.position === "number" ? doc.position : 1, color: typeof doc.color === "string" && doc.color ? doc.color : null, }; }