/**
 * URL slugs (SEO Phase 2). Shared by the backend and the admin dashboard, so both make the same slug.
 *
 *   "Napa Extend" + "665 mg" + "Tablet (Extended Release)" → napa-extend-665-mg-tablet-extended-release
 *   "Amlodipine + Atenolol"                                 → amlodipine-atenolol
 *   "Vitamin B₁₂ 100 µg"                                     → vitamin-b12-100-mcg
 *   "Hydrocortisone 1% Cream"                               → hydrocortisone-1-percent-cream
 */
export function slugify(input: string): string {
  return input
    .normalize('NFKD') // é → e + accent, ₁ → 1
    .replace(/[̀-ͯ]/g, '') // drop the accents
    .replace(/[µμ]/g, 'mc') // µg → mcg
    .replace(/%/g, ' percent ')
    .replace(/&/g, ' and ')
    .toLowerCase()
    .replace(/\+/g, ' ') // combinations: "A + B" → a-b
    .replace(/[^a-z0-9]+/g, '-') // everything else (spaces, / . , ( ) Bangla…) → one hyphen
    .replace(/^-+|-+$/g, '')
    .slice(0, 180)
    .replace(/-+$/, '');
}

/** Brand slug = brand name + strength + dosage form. */
export const brandSlug = (name: string, strength: string, form: string) =>
  slugify(`${name} ${strength} ${form}`);

/**
 * Adds a number only when the slug is already taken: napa-500-mg-tablet, napa-500-mg-tablet-2, -3…
 * `taken` answers whether a slug is used by ANOTHER record.
 */
export function uniqueSlug(base: string, taken: (slug: string) => boolean): string {
  const root = base || 'item';
  if (!taken(root)) return root;
  for (let n = 2; ; n++) {
    const candidate = `${root}-${n}`;
    if (!taken(candidate)) return candidate;
  }
}

/** Async version for database checks. */
export async function uniqueSlugAsync(
  base: string,
  taken: (slug: string) => Promise<boolean>,
): Promise<string> {
  const root = base || 'item';
  if (!(await taken(root))) return root;
  for (let n = 2; ; n++) {
    const candidate = `${root}-${n}`;
    if (!(await taken(candidate))) return candidate;
  }
}
