import { supabase } from '@/integrations/supabase/client';
import { invokeWithTracking } from './edgeFunctionTracking';
import type { UploadedImage } from '@/components/upload/EntityMultiImageUploader';
import { logger } from './logger';

export interface CloudflareUploadResponse {
  result: {
    id: string;
    variants: string[];
  };
  success: boolean;
}

// Internal type to track upload status
interface UploadedImageWithFlag extends UploadedImage {
  wasNewlyUploaded?: boolean;
}

/**
 * Uploads pending local images to Cloudflare via Supabase Edge Function
 * @param images Array of UploadedImage objects (mix of local and already uploaded)
 * @returns Array of UploadedImage objects with all images uploaded
 */
export async function uploadPendingImages(images: UploadedImage[]): Promise<UploadedImage[]> {
  // Process all images in parallel for better performance using allSettled
  const uploadPromises = images.map(async (image, index): Promise<UploadedImageWithFlag> => {
    if (image.isLocal && image.file) {
      const fileName = image.file.name;
      
      // Step 1: Get upload URL from our Supabase Edge Function (with tracking)
      const { data: uploadUrlData, error: urlError, requestId } = await invokeWithTracking(
        'upload-image',
        { action: 'get-upload-url' }
      );

      if (urlError || !uploadUrlData?.uploadURL) {
        logger.error('Failed to get upload URL', {
          action: 'upload_pending_images',
          fileName,
          requestId,
          error: urlError?.message || 'Unknown error',
        });
        throw new Error(`Failed to get upload URL for "${fileName}": ${urlError?.message || 'Unknown error'}`);
      }

      logger.info('Got upload URL', {
        action: 'upload_pending_images',
        fileName,
        requestId,
      });

      // Step 2: Upload file directly to Cloudflare
      const formData = new FormData();
      formData.append('file', image.file);

      const uploadResponse = await fetch(uploadUrlData.uploadURL, {
        method: 'POST',
        body: formData,
      });

      if (!uploadResponse.ok) {
        const errorText = await uploadResponse.text();
        logger.error('Cloudflare upload failed', {
          action: 'upload_pending_images',
          fileName,
          status: uploadResponse.status,
          error: errorText,
        });
        throw new Error(`Upload failed for "${fileName}" (status ${uploadResponse.status}): ${errorText}`);
      }

      const result: CloudflareUploadResponse = await uploadResponse.json();

      if (!result.success || !result.result) {
        logger.error('Cloudflare upload unsuccessful', {
          action: 'upload_pending_images',
          fileName,
        });
        throw new Error(`Cloudflare upload returned unsuccessful response for "${fileName}"`);
      }

      logger.info('Image uploaded successfully', {
        action: 'upload_pending_images',
        fileName,
        imageId: result.result.id,
      });

      // Clean up object URL
      URL.revokeObjectURL(image.url);
      
      // Step 3: Return uploaded image metadata with wasNewlyUploaded flag
      return {
        url: `https://cdn.thrillwiki.com/images/${result.result.id}/public`,
        cloudflare_id: result.result.id,
        caption: image.caption,
        isLocal: false,
        wasNewlyUploaded: true // Flag to track newly uploaded images
      };
    } else {
      // Already uploaded, keep as is
      return {
        url: image.url,
        cloudflare_id: image.cloudflare_id,
        caption: image.caption,
        isLocal: false,
        wasNewlyUploaded: false // Pre-existing image
      };
    }
  });

  // Wait for all uploads to settle (succeed or fail)
  const results = await Promise.allSettled(uploadPromises);
  
  // Separate successful and failed uploads
  const successfulUploads: UploadedImageWithFlag[] = [];
  const newlyUploadedImageIds: string[] = []; // Track ONLY newly uploaded images for cleanup
  const errors: string[] = [];

  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      const uploadedImage = result.value;
      successfulUploads.push(uploadedImage);
      // Only track newly uploaded images for potential cleanup
      if (uploadedImage.wasNewlyUploaded && uploadedImage.cloudflare_id) {
        newlyUploadedImageIds.push(uploadedImage.cloudflare_id);
      }
    } else {
      errors.push(result.reason?.message || `Upload ${index + 1} failed`);
    }
  });

  // If any uploads failed, clean up ONLY newly uploaded images and throw error
  if (errors.length > 0) {
    if (newlyUploadedImageIds.length > 0) {
      logger.error('Some uploads failed, cleaning up', {
        action: 'upload_pending_images',
        newlyUploadedCount: newlyUploadedImageIds.length,
        failureCount: errors.length,
      });
      
      // Attempt cleanup in parallel with detailed error tracking
      const cleanupResults = await Promise.allSettled(
        newlyUploadedImageIds.map(imageId => 
          invokeWithTracking('upload-image', {
            action: 'delete',
            imageId,
          })
        )
      );

      // Track cleanup failures for better debugging
      const cleanupFailures = cleanupResults.filter(r => r.status === 'rejected');
      if (cleanupFailures.length > 0) {
        logger.error('Failed to cleanup images', {
          action: 'upload_pending_images_cleanup',
          cleanupFailures: cleanupFailures.length,
          totalCleanup: newlyUploadedImageIds.length,
          orphanedImages: newlyUploadedImageIds.filter((_, i) => cleanupResults[i].status === 'rejected'),
        });
      } else {
        logger.info('Successfully cleaned up images', {
          action: 'upload_pending_images_cleanup',
          cleanedCount: newlyUploadedImageIds.length,
        });
      }
    }

    throw new Error(`Failed to upload ${errors.length} of ${images.length} images: ${errors.join('; ')}`);
  }

  // Remove the wasNewlyUploaded flag before returning
  return successfulUploads.map(({ wasNewlyUploaded, ...image }) => image as UploadedImage);
}
