/**
 * The "(imported)" suffix an import gives the things it creates (ENG-6816, amended by ENG-6850): a new
 * survey is "<name> (imported)", or "<name> (imported N)" with the lowest N not taken; an action class
 * whose name the workspace already uses gets the same treatment. A trailing suffix is stripped first,
 * so importing an imported survey again gives "(imported 2)", never "(imported) (imported)".
 *
 * The suffix is translated (`common.imported_suffix`, `common.imported_suffix_number`), so the
 * caller passes its `t`. Pure: the caller reads the names already taken.
 */

/** The part of `t` the suffix needs, so a caller can pass any translator. */
export type TTranslate = (key: string, options?: Record<string, unknown>) => string;

/** Stands in for the number while the numbered suffix is turned into a pattern. */
const NUMBER_MARK = "\u0000";

const escapeRegExp = (text: string): string => text.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);

const suffix = (t: TTranslate, number: number): string =>
  number === 1 ? t("common.imported_suffix") : t("common.imported_suffix_number", { number: String(number) });

/**
 * A trailing "(imported)" or "(imported N)", in the user's language, matched on a name trimmed first: a
 * leading `\s*` here would backtrack across a long run of spaces from every position in it.
 */
const trailingSuffixPattern = (t: TTranslate): RegExp => {
  const plain = escapeRegExp(t("common.imported_suffix"));
  const [before = "", after = ""] = t("common.imported_suffix_number", { number: NUMBER_MARK })
    .split(NUMBER_MARK)
    .map(escapeRegExp);
  return new RegExp(String.raw`(?:${plain}|${before}\d+${after})$`, "u");
};

/** The longest start `a` and `b` share. */
const sharedStart = (a: string, b: string): string => {
  let length = 0;
  while (length < a.length && length < b.length && a[length] === b[length]) length++;
  return a.slice(0, length);
};

/**
 * What every numbered candidate {@link getImportedName} tries for `name` starts with: the name without
 * its suffix, then the start the two suffixes share ("<name> (imported"). It narrows the lookup of the
 * names taken; escape it for a `LIKE` pattern first (`escapeLikePattern`). With `keepPlainName`, the
 * name as it is is a candidate too, which the lookup has to match exactly.
 */
export const importedNamePrefix = (name: string, t: TTranslate): string => {
  const [beforeNumber = ""] = t("common.imported_suffix_number", { number: NUMBER_MARK }).split(NUMBER_MARK);
  return `${stripImportedSuffix(name, t)} ${sharedStart(t("common.imported_suffix"), beforeNumber)}`;
};

/** The name without a trailing "(imported N)", so suffixes never stack. */
export const stripImportedSuffix = (name: string, t: TTranslate): string => {
  const trimmed = name.trim();
  const match = trailingSuffixPattern(t).exec(trimmed);
  const stripped = match ? trimmed.slice(0, match.index).trim() : trimmed;
  return stripped === "" ? trimmed : stripped;
};

/**
 * The first free name for something imported as `name`. With `keepPlainName`, the name as it is comes
 * first, for an action class that only needs a suffix when its name is taken; a survey always gets one.
 *
 * @param isTaken Whether a candidate is already used where the import creates it.
 */
export const getImportedName = (
  name: string,
  isTaken: (candidate: string) => boolean,
  t: TTranslate,
  { keepPlainName = false }: { keepPlainName?: boolean } = {}
): string => {
  const base = stripImportedSuffix(name, t);
  if (keepPlainName && !isTaken(name)) return name;

  // Terminates: every number tried is a different name, and only finitely many are taken.
  for (let number = 1; ; number++) {
    const candidate = `${base} ${suffix(t, number)}`;
    if (!isTaken(candidate)) return candidate;
  }
};
