// utils/urlHelpers.ts

/**
 * Creates a URL-friendly slug from a title or string
 * Example: "Ad ut neque enim omn" -> "ad-ut-neque-enim-omn"
 */
export const createSlug = (text: string): string => {
  return text
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '') // Remove special characters
    .replace(/\s+/g, '-') // Replace spaces with hyphens
    .replace(/-+/g, '-'); // Replace multiple hyphens with single hyphen
};

/**
 * Creates an SEO-friendly URL slug with full UUID
 * Example: "Ad ut neque enim omn", "e7d611b6-853b-4785-b508-599eeed2af92" -> "ad-ut-neque-enim-omn-e7d611b6-853b-4785-b508-599eeed2af92"
 */
export const getSlugWithId = (title: string, id: string) => {
  return `${createSlug(title)}-${id}`;
};

/**
 * Extracts the slug from a slug+id string (removes the last part which is the UUID)
 * Example: "ad-ut-neque-enim-omn-e7d611b6-853b-4785-b508-599eeed2af92" -> "ad-ut-neque-enim-omn"
 */
export const extractSlugFromSlugAndId = (slugAndId: string): string => {
  const parts = slugAndId.split('-');
  // Remove the last 5 parts (UUID is 5 segments when split by hyphen)
  for (let i = 0; i < 5; i++) {
    parts.pop();
  }
  return parts.join('-');
};

/**
 * Extracts the full UUID from a slug+id string
 * Example: "ad-ut-neque-enim-omn-e7d611b6-853b-4785-b508-599eeed2af92" -> "e7d611b6-853b-4785-b508-599eeed2af92"
 */
export const extractIdFromSlug = (slugAndId: string): string | null => {
  const parts = slugAndId.split('-');

  if (parts.length < 5) return null;

  const id = parts.slice(-5).join('-');

  const uuidRegex =
    /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

  return uuidRegex.test(id) ? id : null;
};