import { asLookupRows } from "./fanavaran-hull-expertise-lookups"; export type HullLookupStage = "baseClaim" | "expertise" | "files"; /** Default AccidentCauseId (عدم رعايت حق تقدم) used when the case-selected value * is not present in the live Fanavaran accident-causes lookup. */ export const FANAVARAN_HULL_FALLBACK_ACCIDENT_CAUSE_ID = 6; type LookupField = { row: Record; key: string; lookup: string; path: string; }; /** Validate outbound IDs against responses for this tenant, never a sample ID. */ export async function validateFanavaranHullLookupIds( payload: Record, stage: HullLookupStage, fetchRows: (lookup: string) => Promise, ): Promise { const fields: LookupField[] = []; const add = ( row: Record, key: string, lookup: string, path = key, required = true, ) => { if (required || row[key] != null) fields.push({ row, key, lookup, path }); }; if (stage === "baseClaim") { for (const [key, lookup] of Object.entries({ AccidentCityId: "cities", AccidentReportTypeId: "accident-report-type", AccidentCauseId: "accident-causes", AccidentTypeId: "vehicle-hull-accident-types", CulpritTypeId: "vehicle-hull-accident-culprit-type", AuthorityCulpritId: "detection-accident-culprits", CulpritLicenceTypeId: "driving-licence-types", AccidentVehicleUsedId: "vehicle-use-types", })) add(payload, key, lookup); for (const key of [ "IsLicenseReplaced", "IsOwnerChanged", "CostSeparationToDmgSections", "IsAccidentOutOfBorder", "IsSurplusArticleEighthLaw", ]) add(payload, key, "ans", key, false); add(payload, "CulpritLicenceCountryId", "countries", undefined, false); add(payload, "CulpritLicenceCityId", "cities", undefined, false); add(payload, "NotifierTypeId", "notifier-type", undefined, false); add(payload, "NotifierRelationId", "notifier-relation", undefined, false); } else if (stage === "files") { add(payload, "FileTypeId", "file-types"); for (const [i, row] of asLookupRows(payload.Files).entries()) add(row, "FileTypeId", "file-types", `Files[${i}].FileTypeId`); } else { for (const [i, row] of asLookupRows(payload.DmgSections).entries()) { const prefix = `DmgSections[${i}]`; add( row, "AccessoryKindId", "car-components", `${prefix}.AccessoryKindId`, ); // Optional: policy often has only the factory-bundle row; null is allowed. add( row, "VehicleHullAccessoryId", "policy-dmg-accessories", `${prefix}.VehicleHullAccessoryId`, false, ); add(row, "DmgKindId", "vehicle-hull-dmg-kind", `${prefix}.DmgKindId`); for (const [j, cost] of asLookupRows(row.DmgSectionCosts).entries()) add( cost, "DmgCostKindId", "vehicle-hull-dmg-cost-kinds", `${prefix}.DmgSectionCosts[${j}].DmgCostKindId`, ); } } const sources = new Map[]>(); await Promise.all( [...new Set(fields.map((field) => field.lookup))].map(async (lookup) => { try { sources.set(lookup, asLookupRows(await fetchRows(lookup))); } catch { sources.set(lookup, []); } }), ); const warnings: string[] = []; for (const field of fields) { const raw = field.row[field.key]; const id = raw == null || String(raw).trim() === "" ? NaN : Number(raw); const matched = Number.isSafeInteger(id) && id >= 0 ? sources .get(field.lookup) ?.find( (row) => row.Id != null && Number(row.Id) === id && row.IsActive !== false && (row.IsActive == null || Number(row.IsActive) !== 0), ) : undefined; if (!matched) { // For AccidentCauseId: auto-correct to the fallback instead of only warning, // because سنهاب rejects unrecognised cause IDs with a hard error. if (field.key === "AccidentCauseId" && stage === "baseClaim") { const fallbackId = FANAVARAN_HULL_FALLBACK_ACCIDENT_CAUSE_ID; const fallbackRow = sources .get(field.lookup) ?.find( (row) => row.Id != null && Number(row.Id) === fallbackId && row.IsActive !== false && (row.IsActive == null || Number(row.IsActive) !== 0), ); field.row[field.key] = fallbackId; warnings.push( `${field.path}=${raw ?? "(missing)"} is not in the current ${field.lookup} API response; replaced with fallback AccidentCauseId=${fallbackId}${fallbackRow ? ` («${fallbackRow.Caption ?? fallbackRow.Name ?? fallbackId}»)` : ""}.`, ); } else { warnings.push( `${field.path}=${raw ?? "(missing)"} is not in the current ${field.lookup} API response.`, ); } } else { field.row[field.key] = Number(matched.Id); } } return warnings; }