export function isFreightAmountOverridden(
  amount: number,
  originalAmount: number | null | undefined
): boolean {
  if (originalAmount == null || !Number.isFinite(Number(originalAmount))) {
    return false;
  }
  return Math.abs(Number(amount) - Number(originalAmount)) >= 0.005;
}

export function getShippingCostByType(
  shippingCosts: Array<{ shipment_type: number; amount?: number | string; original_amount?: number | string | null }> | undefined,
  shipmentType: number
) {
  if (!shippingCosts?.length) return null;
  return shippingCosts.find((c) => Number(c.shipment_type) === shipmentType) ?? null;
}

export function getOriginalAmountFromShippingCost(
  cost: { amount?: number | string; original_amount?: number | string | null } | null | undefined
): number | null {
  if (!cost) return null;
  if (cost.original_amount != null && cost.original_amount !== '') {
    const original = Number(cost.original_amount);
    return Number.isFinite(original) ? original : null;
  }
  const amount = Number(cost.amount ?? 0);
  return Number.isFinite(amount) ? amount : null;
}

export type LineItemForFreightCalc = {
  product_id?: number | string | null;
  freight?: number | string | null;
  product_type?: number | string | null;
  supplier_country_id?: number | string | null;
  default_supplier_country_id?: number | string | null;
};

const AUSTRALIA_COUNTRY_ID = 1;
const PRODUCT_TYPE_BUNDLE = 2;

/** Live rollup from line freight — use for override tooltip (not stored original_amount). */
export function calculateHeaderFreightFromLineItems(
  products: LineItemForFreightCalc[] | undefined
): { procurement: number; international: number } {
  let procurement = 0;
  let international = 0;

  for (const detail of products || []) {
    if ('product_id' in detail) {
      const id = detail.product_id;
      if (id == null || id === '' || Number(id) <= 0) continue;
    }

    const freight = Number(detail.freight ?? 0) || 0;
    const productType =
      detail.product_type != null && detail.product_type !== ''
        ? Number(detail.product_type)
        : null;
    const countryId =
      detail.supplier_country_id != null && detail.supplier_country_id !== ''
        ? Number(detail.supplier_country_id)
        : detail.default_supplier_country_id != null && detail.default_supplier_country_id !== ''
          ? Number(detail.default_supplier_country_id)
          : null;

    if (productType === PRODUCT_TYPE_BUNDLE) {
      procurement += freight;
      continue;
    }

    if (countryId === null || countryId === AUSTRALIA_COUNTRY_ID) {
      procurement += freight;
    } else if (countryId !== AUSTRALIA_COUNTRY_ID) {
      international += freight;
    }
  }

  return {
    procurement: roundFreightAmount(procurement),
    international: roundFreightAmount(international),
  };
}

export function roundFreightAmount(value: number | string | null | undefined): number {
  const parsed = Number(value);
  if (!Number.isFinite(parsed) || parsed < 0) return 0;
  return Math.round(parsed * 100) / 100;
}

/** Always send both header freight values so saving one field does not zero the other. */
export function buildHeaderFreightPatchPayload(
  procurementInput: number | string | null | undefined,
  internationalInput: number | string | null | undefined
): { procurement_freight: number; international_freight: number } {
  return {
    procurement_freight: roundFreightAmount(procurementInput),
    international_freight: roundFreightAmount(internationalInput),
  };
}

export function syncHeaderFreightInputsFromCosts(
  shippingCosts: Array<{ shipment_type: number; amount?: number | string }> | undefined,
  targets: {
    procurement: { value: number };
    international: { value: number };
  }
) {
  const procurement = getShippingCostByType(shippingCosts, 2);
  const international = getShippingCostByType(shippingCosts, 1);
  if (procurement) {
    targets.procurement.value = roundFreightAmount(procurement.amount);
  }
  if (international) {
    targets.international.value = roundFreightAmount(international.amount);
  }
}
