/**
 * Fix mixed content warnings by upgrading HTTP image URLs to HTTPS
 * This handles image URLs stored in the database as http:// which cause
 * browser warnings when loaded from HTTPS pages.
 */
export function fixImageUrl(url: string | null | undefined): string | null | undefined {
  if (!url || typeof url !== 'string') return url;
  return url.replace(/^http:\/\//i, 'https://');
}

/**
 * Recursively fix all image URL fields in an object
 * Common fields: imageUrl, mainImageUrl, coverImageUrl, thumbnailUrl, etc.
 */
export function fixImageUrls(data: any): any {
  if (!data) return data;

  if (Array.isArray(data)) {
    return data.map(item => fixImageUrls(item));
  }

  if (typeof data === 'object') {
    const fixed: any = {};
    for (const [key, value] of Object.entries(data)) {
      // Fix any field that looks like an image URL
      if (
        (key.toLowerCase().includes('image') ||
         key.toLowerCase().includes('photo') ||
         key.toLowerCase().includes('picture')) &&
        typeof value === 'string'
      ) {
        fixed[key] = fixImageUrl(value);
      } else if (typeof value === 'object') {
        fixed[key] = fixImageUrls(value);
      } else {
        fixed[key] = value;
      }
    }
    return fixed;
  }

  return data;
}
