/**
 * Utility functions for generating and handling URL slugs
 */

/**
 * Generate a URL-friendly slug from a localized name object
 * Uses English name, falls back to Amharic if English is not available
 */
export const generateSlugFromLocalizedName = (name: {
  en?: string;
  am?: string;
}): string => {
  const text = name.en || name.am || "";
  return generateSlug(text);
};

/**
 * Generate a URL-friendly slug from text
 * - Converts to lowercase
 * - Replaces spaces with hyphens
 * - Removes special characters
 * - Handles multiple consecutive hyphens
 */
export const generateSlug = (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
    .replace(/^-+|-+$/g, ""); // Remove leading/trailing hyphens
};

/**
 * Create a unique slug by appending ID suffix
 * Format: "plan-name-abc123"
 */
export const createUniqueSlug = (text: string, id: string): string => {
  const baseSlug = generateSlug(text);
  const shortId = id.slice(0, 8); // Use first 8 chars of UUID
  return `${baseSlug}-${shortId}`;
};

/**
 * Extract ID from a unique slug
 * Format: "plan-name-abc123" -> "abc123"
 */
export const extractIdFromSlug = (slug: string): string => {
  const parts = slug.split("-");
  return parts[parts.length - 1]; // Return last part (the ID)
};

/**
 * Check if a string is a UUID
 */
export const isUUID = (str: string): boolean => {
  const uuidRegex =
    /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
  return uuidRegex.test(str);
};

/**
 * Parse year from URL parameter
 * Handles both year numbers (2024) and UUIDs (for backward compatibility)
 */
export const parseYearParam = (yearParam: string): {
  isYear: boolean;
  value: string;
} => {
  // Check if it's a 4-digit year
  if (/^\d{4}$/.test(yearParam)) {
    return { isYear: true, value: yearParam };
  }
  // Otherwise treat as UUID
  return { isYear: false, value: yearParam };
};

/**
 * Parse slug parameter
 * Handles both slugs and UUIDs (for backward compatibility)
 */
export const parseSlugParam = (
  slugParam: string
): { isSlug: boolean; id: string } => {
  if (isUUID(slugParam)) {
    // It's a UUID, use directly
    return { isSlug: false, id: slugParam };
  }
  // It's a slug, extract ID
  return { isSlug: true, id: extractIdFromSlug(slugParam) };
};
