/**
 * Media URL and image processing utilities
 *
 * This module provides functions for generating and processing image URLs
 * with support for dynamic resizing and fallback images.
 */

/**
 * Base media server URL
 *
 * The CDN or media server endpoint where images are hosted.
 * Used as the base for constructing full image URLs.
 *
 * @example 'https://media.guglu.ca'
 */
const MediaUrl = 'https://media.guglu.ca';

/**
 * Default fallback image URL
 *
 * Shown when no image is available or the provided URL is invalid.
 * Should be a generic placeholder image that works in all contexts.
 */
const DEFAULT_FALLBACK_IMAGE = 'https://guglu.ca/static/images/noPic.jpg';

/**
 * Creates a properly formatted image URL with dynamic resizing
 *
 * This function processes image URLs to ensure they are valid, properly formatted,
 * and optionally resized. It handles various input scenarios:
 * 1. Null/empty URLs → Returns fallback image
 * 2. Full HTTP URLs → Returns as-is (assumes already processed)
 * 3. Relative paths → Prepends media server URL and adds resize parameter
 *
 * @param url - Input image URL (can be null, full URL, or relative path)
 * @returns Fully qualified image URL ready for use in img src
 *
 * @example
 * // Null URL → Fallback
 * createImageUrl(null); // 'https://guglu.ca/static/images/noPic.jpg'
 *
 * @example
 * // Full URL → Returns as-is
 * createImageUrl('https://example.com/image.jpg'); // 'https://example.com/image.jpg'
 *
 * @example
 * // Relative path → Adds media URL and resize
 * createImageUrl('/uploads/avatar.jpg'); // 'https://media.guglu.ca/1024x/uploads/avatar.jpg'
 *
 * @example
 * // Already has media URL → Updates resize parameter
 * createImageUrl('https://media.guglu.ca/original/uploads/avatar.jpg');
 * // 'https://media.guglu.ca/1024x/uploads/avatar.jpg'
 *
 * @note The '/1024x' prefix suggests dynamic width-based resizing to 1024px width
 * @note Consider adding height parameter or aspect ratio preservation
 * @note Ensure media server supports the '/1024x' resize syntax
 */
export const createImageUrl = (url: string | null): string => {
  // Case 1: No URL provided - return fallback image
  if (!url) {
    return DEFAULT_FALLBACK_IMAGE;
  }

  // Case 2: Already a full URL (http/https) - return as-is
  // This assumes external URLs or already-processed URLs don't need modification
  if (url.startsWith('http')) {
    return url;
  }

  // Case 3: URL already starts with media server URL
  // Replace existing resize prefix or add new one
  if (url.startsWith(MediaUrl)) {
    // Extract path after media URL and prepend resize parameter
    const pathWithoutMediaUrl = url.split(MediaUrl)[1];
    return `${MediaUrl}/1024x${pathWithoutMediaUrl}`;
  }

  // Case 4: Relative path - prepend media URL and resize parameter
  return `${MediaUrl}/1024x${url}`;
};
