import type { Location, LocationListItem } from "@/domain/locations/types/location"; function readString(record: Record, ...keys: string[]): string { for (const key of keys) { const value = record[key]; if (typeof value === "string") { return value; } if (typeof value === "number") { return String(value); } } return ""; } function readId(record: Record): string | number { const value = record.id ?? record.Id; if (typeof value === "string" || typeof value === "number") { return value; } return ""; } function readOptionalId(record: Record): string | number { const value = record.accountId ?? record.AccountId; if (typeof value === "string" || typeof value === "number") { return value; } return ""; } export function mapLocationListItem(raw: unknown): LocationListItem { const item = (typeof raw === "object" && raw !== null ? raw : {}) as Record; return { id: readId(item), name: readString(item, "name", "Name"), address: readString(item, "address", "Address"), city: readString(item, "city", "City"), state: readString(item, "state", "State"), zipCode: readString(item, "zipCode", "ZipCode", "Zip"), phone: readString(item, "phone", "Phone"), contact: readString(item, "contact", "Contact", "contactPerson", "ContactPerson"), contactEmail: readString(item, "contactEmail", "ContactEmail"), status: readString(item, "status", "Status"), accountId: readOptionalId(item), }; } export function mapLocationListItems(rawItems: unknown[]): LocationListItem[] { return rawItems.map(mapLocationListItem); } export function mapLocation(raw: unknown): Location { const item = (typeof raw === "object" && raw !== null ? raw : {}) as Record; return { id: readId(item) || undefined, name: readString(item, "name", "Name") || undefined, address: readString(item, "address", "Address") || undefined, city: readString(item, "city", "City") || undefined, state: readString(item, "state", "State") || undefined, zipCode: readString(item, "zipCode", "ZipCode", "Zip") || undefined, phone: readString(item, "phone", "Phone") || undefined, contact: readString(item, "contact", "Contact") || undefined, contactEmail: readString(item, "contactEmail", "ContactEmail") || undefined, status: readString(item, "status", "Status") || undefined, accountId: readOptionalId(item) || undefined, }; } export function mapLocationToBackend(location: unknown): Record { const item = (typeof location === "object" && location !== null ? location : {}) as Record< string, unknown >; const payload: Record = { name: item.name ?? "", address: item.address ?? "", city: item.city ?? "", state: item.state ?? "", zipCode: item.zipCode ?? "", phone: item.phone ?? "", contact: item.contact ?? "", contactEmail: item.contactEmail ?? "", status: item.status ?? "Active", accountId: item.accountId ?? "", }; const id = item.id ?? item.Id; if (typeof id === "string" || typeof id === "number") { payload.id = id; } return payload; }