function normalizeSpace(value) {
  return String(value ?? "")
    .replace(/\u00a0/g, " ")
    .replace(/[\s\u3000]+/gu, " ")
    .trim();
}

const SEARCH_QUERY_NOISE_PATTERN = /^(待确认|未知|通用|暂无|无|空|n\/?a|na|none|null)$/i;

export function compact1688SearchKeyword(value) {
  const normalized = normalizeSpace(value);
  return normalized.replace(/[\s\u3000]+/gu, "");
}

function dedupeList(values) {
  const seen = new Set();
  const output = [];

  for (const value of values) {
    const normalized = compact1688SearchKeyword(value).toLowerCase();
    if (!normalized || seen.has(normalized)) {
      continue;
    }

    seen.add(normalized);
    output.push(normalizeSpace(value));
  }

  return output;
}

export function buildSearchQueryVariants(query, options = {}) {
  const normalizedQuery = normalizeSpace(query);
  const compactedQuery = compact1688SearchKeyword(normalizedQuery);
  if (!compactedQuery) {
    return [];
  }

  if (options.strict === true) {
    return [compactedQuery];
  }

  const tokens = dedupeList(normalizedQuery.split(/\s+/).map((item) => normalizeSpace(item)).filter(Boolean));
  const variants = [];
  const pushVariant = (value) => {
    const normalized = compact1688SearchKeyword(value);
    if (!normalized || variants.includes(normalized)) {
      return;
    }

    variants.push(normalized);
  };

  pushVariant(normalizedQuery);

  const cleanedTokens = tokens.filter((token) => !SEARCH_QUERY_NOISE_PATTERN.test(token));
  pushVariant(cleanedTokens.join(""));

  if (cleanedTokens.length >= 2) {
    pushVariant(cleanedTokens.slice(0, 2).join(""));
  }

  if (cleanedTokens.length >= 1) {
    pushVariant(cleanedTokens[0]);
  }

  return variants.length > 0 ? variants : [normalizedQuery];
}
