import { BadRequestException } from '@nestjs/common';

/**
 * 挡位标签标准化：将输入统一整理为可稳定比较和展示的字符串。
 */
export function normalizePressureLabel(value: unknown, fieldName: string) {
  const raw =
    typeof value === 'string' || typeof value === 'number'
      ? String(value).trim()
      : '';

  if (!raw) {
    throw new BadRequestException(`${fieldName} 不能为空`);
  }
  if (!/^\d+(\.\d+)?$/.test(raw)) {
    throw new BadRequestException(`${fieldName} 必须是合法挡位标签`);
  }

  const [integerPart, fractionPart = ''] = raw.split('.');
  const normalizedInteger = integerPart.replace(/^0+(?=\d)/, '') || '0';
  const normalizedFraction = fractionPart.replace(/0+$/, '');

  return normalizedFraction
    ? `${normalizedInteger}.${normalizedFraction}`
    : normalizedInteger;
}

/**
 * 挡位标签比较：按数值大小排序，数值相同再按标准字符串比较。
 */
export function comparePressureLabel(left: string, right: string) {
  const leftNumber = Number(left);
  const rightNumber = Number(right);

  if (leftNumber !== rightNumber) {
    return leftNumber - rightNumber;
  }

  return left.localeCompare(right, 'en');
}

/**
 * 挡位列表标准化：去重、排序。
 */
export function normalizePressureLabelList(
  values: unknown[] | undefined,
  fieldName: string,
) {
  if (!Array.isArray(values) || values.length === 0) {
    return [];
  }

  return Array.from(
    new Set(values.map((value) => normalizePressureLabel(value, fieldName))),
  ).sort(comparePressureLabel);
}
