import type { Service } from "@/domain/services/types/service"; import type { WOType } from "@/domain/work-orders/types/work-order-wizard"; function asRecord(raw: unknown): Record { return typeof raw === "object" && raw !== null ? (raw as Record) : {}; } function readId(item: Record): string | number { const value = item.id ?? item.Id; return typeof value === "string" || typeof value === "number" ? value : ""; } function readString(item: Record, ...keys: string[]): string { for (const key of keys) { const value = item[key]; if (typeof value === "string") return value.trim(); } return ""; } function readBool(item: Record, ...keys: string[]): boolean { for (const key of keys) { const value = item[key]; if (typeof value === "boolean") return value; } return false; } function mapWorkOrderType(value: unknown): WOType | null { if (typeof value === "number") { return value === 2 ? "PM" : value === 3 ? "Emergency" : value === 6 ? "Reactive" : null; } if (typeof value === "string") { const normalized = value.trim().toLowerCase(); return normalized === "pm" || normalized === "preventivemaintenance" ? "PM" : normalized === "emergency" ? "Emergency" : normalized === "reactive" ? "Reactive" : null; } return null; } export function mapService(raw: unknown): Service { const item = asRecord(raw); const types = item.supportedWorkOrderTypes ?? item.SupportedWorkOrderTypes; return { id: readId(item), name: readString(item, "name", "Name"), trade: readString(item, "trade", "Trade"), iconKey: readString(item, "iconKey", "IconKey"), requiresCompletionDocument: readBool( item, "requiresCompletionDocument", "RequiresCompletionDocument", ), isActive: readBool(item, "isActive", "IsActive"), supportedWorkOrderTypes: Array.isArray(types) ? types.flatMap((value) => { const mapped = mapWorkOrderType(value); return mapped ? [mapped] : []; }) : [], }; } export function mapServices(raw: unknown): Service[] { return Array.isArray(raw) ? raw.map(mapService).filter((service) => service.id !== "") : []; }