import apiClient from '@services/api';

/**
 * Utility functions for handling images
 */
const imageUtils = {
  /**
   * Get a full URL for an image path
   * @param {string} imagePath - The image path or URL
   * @param {string} [defaultImage] - Default image to use if the path is invalid
   * @returns {string} - The full image URL
   */
  getImageUrl: (imagePath, defaultImage = '/placeholder.jpg') => {
    if (!imagePath) return defaultImage;
    
    // If it's already a complete URL, return it as is
    if (imagePath.startsWith('http')) {
      return imagePath;
    }
    
    // The base API URL from environment or default
    // Remove '/api' from the end if present, as we'll add the full path ourselves
    const apiBaseUrl = import.meta.env.VITE_API_URL 
      ? import.meta.env.VITE_API_URL.replace(/\/api$/, '')
      : '';
    
    // If it starts with '/uploads', it's a relative path to our API
    if (imagePath.startsWith('/uploads')) {
      return `${apiBaseUrl}${imagePath}`;
    }
    
    // If it starts with '/images', it's a direct path to our static files
    if (imagePath.startsWith('/images')) {
      return `${apiBaseUrl}${imagePath}`;
    }
    
    // Otherwise, treat it as a relative path
    return imagePath.startsWith('/') ? `${apiBaseUrl}${imagePath}` : `${apiBaseUrl}/${imagePath}`;
  },
  
  /**
   * Upload a single image file
   * @param {File} file - The image file to upload
   * @param {Object} [options] - Upload options
   * @param {string} [options.apiKey] - API key for authentication
   * @param {boolean} [options.isProductImage] - Whether this is a product image
   * @returns {Promise<Object>} - The upload response
   */
  uploadImage: async (file, options = {}) => {
    const { apiKey, isProductImage = false } = options;
    console.log("uploadImage", options);
    
    const formData = new FormData();
    formData.append('image', file);
    
    const headers = {};
    if (apiKey) {
      headers['X-API-Key'] = apiKey;
    }
    
    // Use the appropriate endpoint based on image type
    const endpoint = isProductImage ? '/image/product' : '/image/upload';
    
    try {
      console.log(`Uploading image to: ${endpoint}`);
      const response = await apiClient.post(endpoint, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          ...headers
        }
      });
      
      console.log('Upload response:', response.data);
      return response.data;
    } catch (error) {
      console.error('Image upload failed:', error);
      console.error('Response status:', error.response?.status);
      console.error('Response data:', error.response?.data);
      throw error.response?.data || { message: 'Image upload failed' };
    }
  },
  
  /**
   * Upload multiple image files
   * @param {Array<File>} files - The image files to upload
   * @param {Object} [options] - Upload options
   * @param {string} [options.apiKey] - API key for authentication
   * @returns {Promise<Object>} - The upload response
   */
  uploadMultipleImages: async (files, options = {}) => {
    const { apiKey } = options;
    
    const formData = new FormData();
    files.forEach(file => {
      formData.append('images', file);
    });
    
    const headers = {};
    if (apiKey) {
      headers['X-API-Key'] = apiKey;
    }
    
    try {
      console.log('Uploading multiple images');
      const response = await apiClient.post('/image/products', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          ...headers
        }
      });
      
      console.log('Multiple image upload response:', response.data);
      return response.data;
    } catch (error) {
      console.error('Multiple image upload failed:', error);
      console.error('Response status:', error.response?.status);
      console.error('Response data:', error.response?.data);
      throw error.response?.data || { message: 'Multiple image upload failed' };
    }
  },
  
  /**
   * Delete an image by filename
   * @param {string} filename - The filename to delete
   * @param {Object} [options] - Delete options
   * @param {string} [options.apiKey] - API key for authentication
   * @returns {Promise<Object>} - The delete response
   */
  deleteImage: async (filename, options = {}) => {
    const { apiKey } = options;
    
    const headers = {};
    if (apiKey) {
      headers['X-API-Key'] = apiKey;
    }
    
    try {
      const response = await apiClient.delete(`/image/product/${filename}`, {
        headers
      });
      
      return response.data;
    } catch (error) {
      console.error('Image deletion failed:', error);
      throw error.response?.data || { message: 'Image deletion failed' };
    }
  },
  
  /**
   * Extract filename from an image path
   * @param {string} imagePath - The image path
   * @returns {string|null} - The filename or null if not found
   */
  getFilenameFromPath: (imagePath) => {
    if (!imagePath) return null;
    
    // Try to extract the filename from the path
    const matches = imagePath.match(/\/([^\/]+)$/);
    return matches ? matches[1] : null;
  }
};

export default imageUtils;