/**
 * Apply company OEM / material fields from cart-quote-order product search results.
 */
export function applyMappingFromSearchProduct(
  row: Record<string, unknown>,
  selectedProduct: Record<string, unknown>
): void {
  if (selectedProduct.compatible_product_id != null) {
    row.compatible_product_id = Number(selectedProduct.compatible_product_id);
  }

  const material =
    selectedProduct.prefill_material_number ??
    selectedProduct.matched_material_number ??
    null;

  if (material !== undefined && material !== null && material !== '') {
    row.material_number = material;
  }
}

/**
 * Apply company OEM / material fields from compatible_products (company-mapping API).
 */
export function applyMappingFromApi(
  row: Record<string, unknown>,
  mapping: Record<string, unknown> | null | undefined,
  masterSku?: string | null
): void {
  if (!mapping) {
    row.product_company_mapping_id = null;
    return;
  }

  const mappingId = mapping.compatible_product_id ?? mapping.id ?? null;
  row.product_company_mapping_id = mappingId;

  if (mapping.compatible_product_id != null) {
    row.compatible_product_id = Number(mapping.compatible_product_id);
  }

  row.material_number = mapping.material_number ?? null;

  const oem = String(mapping.oem_number ?? '').trim();
  const master = String(masterSku ?? row.sku ?? '').trim();
  if (oem !== '' && master !== '' && oem.toLowerCase() !== master.toLowerCase()) {
    row.customer_part_number = oem;
  }
}
