import { DeliveryOption } from '../models';

export function normalizeOptionalNumber(value: unknown): number | undefined {
  if (value === null || value === undefined || value === '') {
    return undefined;
  }

  const normalized = typeof value === 'number'
    ? value
    : Number(String(value).replace(',', '.'));

  return Number.isFinite(normalized) ? normalized : undefined;
}

function normalizeOptionalString(value: unknown): string {
  if (typeof value === 'string') {
    return value.trim();
  }

  if (typeof value === 'number' || typeof value === 'bigint') {
    return String(value);
  }

  return '';
}

function asRecord(value: unknown): Record<string, unknown> | null {
  return value !== null && typeof value === 'object' && !Array.isArray(value)
    ? value as Record<string, unknown>
    : null;
}

export function normalizeDeliveryOption(value: unknown): DeliveryOption | null {
  const source = asRecord(value);
  if (!source) {
    return null;
  }

  const deliveryPlace = normalizeOptionalString(
    source['deliveryPlace'] ?? source['delivery_place'] ?? source['deliveryplace']
  );
  const deliveryTime = normalizeOptionalString(
    source['deliveryTime'] ?? source['delivery_time'] ?? source['deliverytime']
  );
  const deliveryPrice = normalizeOptionalNumber(
    source['deliveryPrice'] ?? source['delivery_price'] ?? source['deliveryprice']
  );

  if (deliveryPrice === undefined && !deliveryPlace && !deliveryTime) {
    return null;
  }

  return {
    deliveryPrice: deliveryPrice ?? 0,
    deliveryPlace,
    deliveryTime,
  };
}