import { canonicalize, MAX_QUERY_CHARS, MIN_QUERY_CHARS } from "../../shared/contract.js";
import type { NormalizedQuery } from "./types.js";

/** "09.C881-11" -> "09C88111"; returns null for input too short (or long) to be a part number. */
export function normalizeQuery(input: string): NormalizedQuery | null {
  const raw = input.trim();
  const canonical = canonicalize(raw);
  if (canonical.length < MIN_QUERY_CHARS || canonical.length > MAX_QUERY_CHARS) return null;
  return { raw, canonical };
}

/** Store price text to number: "8,24 €" -> 8.24, "1 234,56" -> 1234.56. NaN if hopeless. */
export function parsePriceEur(text: string): number {
  const cleaned = text
    .replace(/[€\s]/g, "") // \s covers the nbsp stores use as a thousands separator
    .replace(/\.(?=\d{3}(\D|$))/g, "") // 1.234,56 thousands dot
    .replace(",", ".");
  const m = cleaned.match(/\d+(\.\d+)?/);
  return m ? Number(m[0]) : NaN;
}
