/**
 * Utility functions for uploading images from URLs
 * 
 * NOTE: CORS-limited; will be replaced with backend implementation.
 * Flow currently hidden (not removed) from frontend.
 */

import {
  DEFAULT_ALLOWED_CONTENT_TYPES,
  MIME_TYPE_TO_EXTENSION,
  DEFAULT_IMAGE_EXTENSION,
} from '../v2Components/CapImageUrlUpload/constants';

/**
 * Fetches an image from a URL
 * 
 * @param {string} url - The image URL to fetch
 * @returns {Promise<Response>} - The fetch response object
 * @throws {Error} - If the fetch fails (network/CORS error)
 */
export const fetchImageFromUrl = async (url) => {
  const trimmedUrl = url?.trim() || '';
  
  if (!trimmedUrl) {
    throw new Error('URL is required');
  }

  // CORS-limited: fails for images without proper CORS headers
  const response = await fetch(trimmedUrl, {
    method: 'GET',
    redirect: 'follow',
    mode: 'cors',
  });

  if (!response.ok) {
    throw new Error(`Failed to fetch image: ${response.status} ${response.statusText}`);
  }

  return response;
};

/**
 * Helper function to upload image from URL
 * Fetches image, validates content type and size, converts to File, and uploads via uploadAsset
 * 
 * @param {string} url - The image URL to upload
 * @param {Function} formatMessage - React Intl formatMessage function
 * @param {Object} messages - React Intl messages object
 * @param {Function} uploadAssetFn - Function to upload the asset (file, type, fileParams)
 * @param {string} fileNamePrefix - Prefix for the generated file name
 * @param {number} maxSize - Maximum file size in bytes
 * @param {string[]} allowedContentTypes - Array of allowed MIME types (defaults to DEFAULT_ALLOWED_CONTENT_TYPES)
 * @returns {Promise<{success: boolean, error: string}>} - Result object with success status and error message
 * 
 * @example
 * const result = await uploadImageFromUrlHelper(
 *   'https://example.com/image.jpg',
 *   formatMessage,
 *   messages,
 *   uploadAsset,
 *   'my-image',
 *   5000000,
 *   ['image/jpeg', 'image/png']
 * );
 */
export const uploadImageFromUrlHelper = async (
  url,
  formatMessage,
  messages,
  uploadAssetFn,
  fileNamePrefix,
  maxSize,
  allowedContentTypes = DEFAULT_ALLOWED_CONTENT_TYPES,
) => {
  const trimmedUrl = url?.trim() || '';
  
  try {
    const response = await fetchImageFromUrl(trimmedUrl);

    // Validate Content-Type
    const contentType = response.headers?.get('Content-Type') || '';
    const normalizedContentType = contentType.split(';')[0].toLowerCase().trim();
    
    if (!allowedContentTypes.includes(normalizedContentType)) {
      return {
        success: false,
        error: formatMessage(messages.imageTypeInvalid),
      };
    }

    const blob = await response.blob();
    
    if (blob.size > maxSize) {
      return {
        success: false,
        error: formatMessage(messages.imageSizeInvalid),
      };
    }

    // Load image to get dimensions and verify validity
    return new Promise((resolve) => {
      const img = new Image();
      const objectUrl = URL.createObjectURL(blob);
      
      img.onload = () => {
        const extension = MIME_TYPE_TO_EXTENSION[normalizedContentType] || DEFAULT_IMAGE_EXTENSION;
        const fileName = `${fileNamePrefix}.${extension}`;
        const file = new File([blob], fileName, { type: blob.type });
        const fileParams = {
          width: img.width,
          height: img.height,
          error: false,
        };
        
        uploadAssetFn(file, 'image', fileParams);
        URL.revokeObjectURL(objectUrl);
        
        resolve({
          success: true,
          error: '',
        });
      };
      
      img.onerror = () => {
        URL.revokeObjectURL(objectUrl);
        resolve({
          success: false,
          error: formatMessage(messages.imageLoadError),
        });
      };
      
      img.src = objectUrl;
    });
  } catch (error) {
    return {
      success: false,
      error: formatMessage(messages.imageLoadError),
    };
  }
};

