import { useMemo } from "react"; import { type Resolver } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { vendorCompanyRosterSchema, type VendorCompanyRosterFormValues, } from "@/domain/vendors/schemas/vendor-roster-schema"; import { getSingleStatusOnlyChange } from "@/domain/vendors/use-cases/use-save-vendor-company-roster"; import type { VendorCompanyRoster } from "@/domain/vendors/types/vendor"; function withoutTechnicianStubs( values: VendorCompanyRosterFormValues, ): VendorCompanyRosterFormValues { return { ...values, technicians: values.technicians.filter((technician) => { if (technician === null || typeof technician !== "object" || Array.isArray(technician)) { return true; } const candidate = technician as unknown as Record; const keys = Object.keys(candidate); const isGeneratedStatusStub = keys.length === 1 && keys[0] === "isActive" && typeof candidate.isActive === "boolean"; return !isGeneratedStatusStub; }), }; } export function useVendorRosterResolver( routeRoster: VendorCompanyRoster | undefined, ): Resolver { const strictResolver = useMemo(() => zodResolver(vendorCompanyRosterSchema), []); return useMemo>( () => async (values, context, options) => { const normalizedValues = withoutTechnicianStubs(values); if (routeRoster && getSingleStatusOnlyChange(routeRoster, normalizedValues)) { return { values: normalizedValues, errors: {} }; } return strictResolver(normalizedValues, context, options); }, [routeRoster, strictResolver], ); }