/**
 * Slug Helpers
 *
 * Utilities for generating and validating URL slugs
 */

/**
 * Regex pattern for valid slugs
 * Matches: lowercase alphanumeric with hyphens between segments
 * Examples: "my-page", "page-2", "about"
 */
export const slugPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

/**
 * Sanitize a string into a valid URL slug
 *
 * @param value - Raw string to sanitize
 * @returns Sanitized slug string
 *
 * @example
 * sanitizeSlug('My Page Title') // 'my-page-title'
 * sanitizeSlug('Hello  World!') // 'hello-world'
 * sanitizeSlug('--test--')      // 'test'
 */
export function sanitizeSlug(value: string): string {
  return value
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

/**
 * Build a unique slug from a base value, avoiding collisions with existing slugs
 *
 * @param baseValue - The desired slug base
 * @param usedSlugs - Set of already-used slugs
 * @returns A unique slug string
 *
 * @example
 * const used = new Set(['my-page', 'my-page-2']);
 * buildUniqueSlug('my-page', used) // 'my-page-3'
 *
 * @example
 * const used = new Set(['about']);
 * buildUniqueSlug('About', used) // 'about-2'
 */
export function buildUniqueSlug(
  baseValue: string,
  usedSlugs: Set<string>,
): string {
  const baseSlug = sanitizeSlug(baseValue) || 'page';
  if (!usedSlugs.has(baseSlug)) return baseSlug;

  let suffix = 2;
  while (usedSlugs.has(`${baseSlug}-${suffix}`)) {
    suffix += 1;
  }

  return `${baseSlug}-${suffix}`;
}

/**
 * Build a unique slug from an array of existing slugs
 *
 * @param baseValue - The desired slug base
 * @param existingSlugs - Array of already-used slugs
 * @returns A unique slug string
 *
 * @example
 * buildUniqueSlugFromArray('my-page', ['my-page', 'my-page-2']) // 'my-page-3'
 */
export function buildUniqueSlugFromArray(
  baseValue: string,
  existingSlugs: string[],
): string {
  return buildUniqueSlug(baseValue, new Set(existingSlugs));
}

/**
 * Validate if a string is a valid slug
 *
 * @param value - String to validate
 * @returns true if valid slug format
 */
export function isValidSlug(value: string): boolean {
  return slugPattern.test(value);
}
