import slugify from 'slugify';
import { Song } from '../models/Song.js';

export function slugifyText(text) {
  return slugify(text, { lower: true, strict: true, trim: true });
}

/**
 * Builds a unique slug for a song. If a custom slug was provided by the
 * admin, it's normalized and used as long as it doesn't collide with
 * another song. Otherwise one is generated from "artist title", with a
 * numeric suffix appended on collision.
 */
export async function generateUniqueSlug({ customSlug, artist, title, excludeId = null }) {
  const base = customSlug ? slugifyText(customSlug) : slugifyText(`${artist} ${title}`);

  let candidate = base;
  let suffix = 2;

  while (await Song.slugExists(candidate, excludeId)) {
    candidate = `${base}-${suffix}`;
    suffix += 1;
  }

  return candidate;
}
