/**
 * Helper functions for image handling and preview generation
 */

/**
 * Get the optimal image source URL based on context
 * @param {Object} image - Image object from API or preview object
 * @param {boolean} usePreview - Whether to prefer preview over original (default: true)
 * @returns {string} Image URL
 */
export const getImageSrc = (image, usePreview = true) => {
    if (!image) {
        return '';
    }

    // For preview mode with blob URLs (file upload preview)
    if (image.url && (image.url.startsWith('blob:') || image.url.startsWith('data:'))) {
        return image.url;
    }

    // If previews are enabled and available, use preview
    if (usePreview && image.previewPath) {
        // previewPath is just the filename, not a full path
        const previewFileName = image.previewPath.includes('/') 
            ? image.previewPath.split('/').pop() 
            : image.previewPath;
        return `/api/previews/${previewFileName}`;
    }

    // Fallback chain for original image
    if (image.filePath) {
        return `/api${image.filePath}`;
    }
    
    if (image.fileName) {
        return `/api/download/${image.fileName}`;
    }

    // Legacy fallback
    if (image.remoteUrl) {
        return image.remoteUrl;
    }

    return '';
};

/**
 * Get preview image for a group (first image)
 * @param {Object} group - Group object from API
 * @param {boolean} usePreview - Whether to prefer preview over original
 * @returns {string} Image URL for group preview
 */
export const getGroupPreviewSrc = (group, usePreview = true) => {
    if (!group) {
        return '';
    }

    // Legacy support: direct previewImage field
    if (group.previewImage) {
        return `/api/download/${group.previewImage.split('/').pop()}`;
    }

    // Use first image from group
    if (group.images && group.images.length > 0) {
        return getImageSrc(group.images[0], usePreview);
    }

    return '';
};
