
import { supabase } from '@/integrations/supabase/client';
import { v4 as uuidv4 } from 'uuid';

/**
 * WARNING: EXIF DATA PRESERVATION
 * Do not perform client-side image processing before extracting EXIF metadata.
 */

export const validateImage = (file) => {
  const MAX_SIZE = 5 * 1024 * 1024; // 5MB
  const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

  if (!file) return { valid: false, error: 'No file selected' };
  if (!ALLOWED_TYPES.includes(file.type)) return { valid: false, error: 'Invalid file type. Allowed: JPG, PNG, GIF, WEBP' };
  if (file.size > MAX_SIZE) return { valid: false, error: 'File too large. Max 5MB' };

  return { valid: true };
};

export const getImageDimensions = (file) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      resolve({ width: img.width, height: img.height });
      URL.revokeObjectURL(img.src);
    };
    img.onerror = reject;
    img.src = URL.createObjectURL(file);
  });
};

export const uploadImage = async (file, bucket = 'custom-form-images') => {
  const { valid, error } = validateImage(file);
  if (!valid) throw new Error(error);

  const fileExt = file.name.split('.').pop();
  const fileName = `${uuidv4()}.${fileExt}`;
  const filePath = `${fileName}`;

  const { data, error: uploadError } = await supabase.storage
    .from(bucket)
    .upload(filePath, file);

  if (uploadError) throw uploadError;

  const { data: { publicUrl } } = supabase.storage
    .from(bucket)
    .getPublicUrl(filePath);

  const dimensions = await getImageDimensions(file);

  return {
    url: publicUrl,
    path: filePath,
    width: dimensions.width,
    height: dimensions.height,
    size: file.size,
    type: file.type
  };
};

export const extractImagesFromHtml = (html) => {
  if (!html) return [];
  const div = document.createElement('div');
  div.innerHTML = html;
  const images = div.getElementsByTagName('img');
  return Array.from(images).map(img => ({
    src: img.src,
    alt: img.alt,
    width: img.style.width,
    height: img.style.height,
    alignment: img.style.textAlign || img.parentElement?.style?.textAlign
  }));
};
