import { Order, NormalizedOrderRow } from '../types';

/**
 * Normalizes an order object from the API to a standardized format for the DataGrid.
 * Handles field name variations and provides default values.
 *
 * @param order - Raw order object from API
 * @param index - Index of the order in the array (used for fallback ID)
 * @returns Normalized order row for DataGrid
 */
export function normalizeOrder(
  order: Order,
  index: number
): NormalizedOrderRow {
  const getStringValue = (
    ...values: (string | number | undefined | null)[]
  ): string => {
    for (const value of values) {
      if (value !== undefined && value !== null && value !== '') {
        return String(value);
      }
    }
    return '-';
  };

  const getNumericValue = (
    ...values: (number | string | undefined | null)[]
  ): number => {
    for (const value of values) {
      if (value !== undefined && value !== null && value !== '') {
        const num = typeof value === 'string' ? parseFloat(value) : value;
        if (!isNaN(num)) return num;
      }
    }
    return 0;
  };

  const getOptionalValue = <T>(
    ...values: (T | undefined | null)[]
  ): T | undefined => {
    for (const value of values) {
      if (value !== undefined && value !== null) {
        return value;
      }
    }
    return undefined;
  };

  const normalizePriority = (
    priority: number | string | null | undefined
  ): string | null => {
    if (priority == null) return null;
    const str = String(priority).trim();
    return str === '' ? null : str;
  };

  const orderId = order.orderId || order.id;
  const id = orderId ? String(orderId) : `order-${index}`;

  return {
    id,
    orderId: orderId || index,
    createDate: getOptionalValue<string>(order.createDate, order.createDateIni),
    customerName: getStringValue(order.customerName),
    status: getStringValue(order.status) || 'Pendente',
    orderType: getStringValue(order.orderType, order.type),
    amount: getNumericValue(order.amount),
    invoiceNumber: getStringValue(order.invoiceNumber),
    billingId: getOptionalValue<string>(order.billingId),
    sellerName: getStringValue(order.sellerName),
    deliveryType: getStringValue(order.deliveryType),
    totalWeight: getNumericValue(order.totalWeigth, order.totalWeight),
    fatUserName: getStringValue(order.fatUserName),
    customerId: order.customerId,
    deliveryDate: order.deliveryDate,
    deliveryLocal: getStringValue(order.deliveryLocal),
    masterDeliveryLocal: getStringValue(order.masterDeliveryLocal),
    deliveryPriority: normalizePriority(order.deliveryPriority),
    invoiceDate: order.invoiceDate,
    invoiceHour: getOptionalValue<number | string>(
      order.invoiceHour,
      order['HORA FATURAMENTO']
    ),
    invoiceMinute: getOptionalValue<number | string>(
      order.invoiceMinute,
      order['MINUTO FATURAMENTO']
    ),
    invoiceTime: (() => {
      const hour = getOptionalValue<number | string>(
        order.invoiceHour,
        order['HORA FATURAMENTO']
      );
      const minute = getOptionalValue<number | string>(
        order.invoiceMinute,
        order['MINUTO FATURAMENTO']
      );
      if (hour !== undefined && minute !== undefined) {
        return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
      }
      return undefined;
    })(),
    confirmDeliveryDate: order.confirmDeliveryDate,
    paymentId: order.paymentId,
    paymentName: getStringValue(order.paymentName),
    sellerId: order.sellerId,
    storeId: order.storeId,
    store: getStringValue(order.store),
    partnerId: order.partnerId,
    partnerName: getStringValue(order.partnerName),
    codusur2Name: getStringValue(order.codusur2Name),
    releaseDate: order.releaseDate,
    releaseUserName: getStringValue(order.releaseUserName),
    shipmentDate: order.shipmentDate,
    processOrder: order.processOrder,
    payment: order.payment,
    driver: getStringValue(order.driver),
    orderSaleId: order.orderSaleId,
    carDescription: getStringValue(order.carDescription),
    carrier: getStringValue(order.carrier),
    statusTransfer: order.statusTransfer,
    schedulerDelivery: getStringValue(order.schedulerDelivery),
    fatUserCode: order.fatUserCode,
    fatUserDescription: getStringValue(order.fatUserDescription),
    codEmitente: order.codEmitente,
    emitenteNome: getStringValue(order.emitenteNome),
  };
}
