export type PricePair = {
  market_price: number;
  price: number;
};

export function parsePriceValue(value: unknown): number {
  if (value === null || value === undefined || value === '') {
    return 0;
  }
  const num = Number(value);
  return Number.isFinite(num) ? num : 0;
}

/**
 * 与后端 format_price 一致：第三位小数非 0 则分位进 1，再保留两位小数。
 */
export function formatPriceLikeBackend(value: unknown): number {
  const price = parsePriceValue(value);
  let milli = Math.round(price * 1000);
  if (milli % 10 > 0) {
    milli += 10;
  }
  milli -= milli % 10;
  return Math.round((milli / 1000) * 100) / 100;
}

export function normalizePricePair(pair: PricePair): PricePair {
  return {
    market_price: formatPriceLikeBackend(pair.market_price),
    price: formatPriceLikeBackend(pair.price),
  };
}

export function toPriceUnits(value: unknown): number {
  return Math.round(formatPriceLikeBackend(value) * 100);
}

export function formatPriceDisplay(value: unknown): string {
  return formatPriceLikeBackend(value).toFixed(2);
}

export type PriceDelta = 'up' | 'down' | 'same';

export function getPriceDelta(orig: number, next: number): PriceDelta {
  const a = toPriceUnits(orig);
  const b = toPriceUnits(next);
  if (b > a) {
    return 'up';
  }
  if (b < a) {
    return 'down';
  }
  return 'same';
}

export function isFieldChanged(orig: number, next: number): boolean {
  return getPriceDelta(orig, next) !== 'same';
}

export function isPriceChanged(
  initial: PricePair | undefined,
  current: PricePair,
): boolean {
  if (!initial) {
    return true;
  }
  return (
    isFieldChanged(initial.market_price, current.market_price) ||
    isFieldChanged(initial.price, current.price)
  );
}

export function isMarketGtPrice(current: PricePair): boolean {
  return toPriceUnits(current.market_price) > toPriceUnits(current.price);
}
