export const QC_MEASURE_TYPE = {
  TEMPERATURE: "TEMPERATURE",
  HUMIDITY: "HUMIDITY",
} as const;

export type QcMeasureType = (typeof QC_MEASURE_TYPE)[keyof typeof QC_MEASURE_TYPE];

export function isTemperatureQcItem(row: { name?: string; code?: string }): boolean {
  const name = (row.name ?? "").trim();
  const code = (row.code ?? "").trim();
  return name === "溫度" || code === "溫度" || name.toLowerCase() === "temperature";
}

export function isHumidityQcItem(row: { name?: string; code?: string }): boolean {
  const name = (row.name ?? "").trim();
  const code = (row.code ?? "").trim();
  return name === "濕度" || code === "濕度" || name.toLowerCase() === "humidity";
}

export function isMeasurableQcItem(row: { name?: string; code?: string }): boolean {
  return isTemperatureQcItem(row) || isHumidityQcItem(row);
}

export function resolveMeasureMeta(
  row: { name?: string; code?: string },
): { measureType: QcMeasureType; unit: string } | null {
  if (isTemperatureQcItem(row)) {
    return { measureType: QC_MEASURE_TYPE.TEMPERATURE, unit: "°C" };
  }
  if (isHumidityQcItem(row)) {
    return { measureType: QC_MEASURE_TYPE.HUMIDITY, unit: "%" };
  }
  return null;
}

export function buildQcMeasurementPayload(
  row: {
    name?: string;
    code?: string;
    measurementValue?: number | null;
    measureType?: string;
    unit?: string;
  },
) {
  const meta = resolveMeasureMeta(row);
  return {
    measureType: row.measureType ?? meta?.measureType ?? QC_MEASURE_TYPE.TEMPERATURE,
    value: row.measurementValue ?? null,
    unit: row.unit ?? meta?.unit ?? "°C",
  };
}
