export const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
export const SLUG_MAX_LENGTH = 120;

/** "Airbnb Host: Keep Your Number Private!" becomes "airbnb-host-keep-your-number-private". */
export function slugify(input: string, maxLength = SLUG_MAX_LENGTH) {
  return input
    .normalize("NFKD")
    .replace(/\p{M}/gu, "")
    .toLowerCase()
    .replace(/&/g, " and ")
    .replace(/['’]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, maxLength)
    .replace(/-+$/g, "");
}

/** Appends -2, -3, … until `isTaken` returns false. */
export async function uniqueSlug(
  base: string,
  isTaken: (slug: string) => Promise<boolean>,
) {
  const root = slugify(base) || "untitled";
  if (!(await isTaken(root))) return root;
  for (let suffix = 2; suffix < 1000; suffix++) {
    const tail = `-${suffix}`;
    const candidate = `${root.slice(0, SLUG_MAX_LENGTH - tail.length)}${tail}`;
    if (!(await isTaken(candidate))) return candidate;
  }
  return `${root.slice(0, SLUG_MAX_LENGTH - 9)}-${Date.now().toString(36)}`;
}
