import UIKit
import ComposeApp

/// Helper class for compressing images to meet size requirements
class ImageCompression {
    /// Maximum image size in bytes (200KB)
    /// Change this value to adjust the size limit for all image uploads
    static let maxImageSizeBytes = 200 * 1024 // 200KB

    /// Initial JPEG compression quality
    private static let initialQuality: CGFloat = 0.85

    /// Minimum JPEG compression quality
    private static let minQuality: CGFloat = 0.20

    /// Compress an image to JPEG format with size limit
    /// - Parameter image: The UIImage to compress
    /// - Returns: Compressed image data as Data, or nil if compression fails
    static func compressImage(_ image: UIImage) -> Data? {
        var quality = initialQuality
        var compressedData: Data?

        // Iteratively reduce quality until we meet the size requirement
        while quality >= minQuality {
            compressedData = image.jpegData(compressionQuality: quality)

            if let data = compressedData, data.count <= maxImageSizeBytes {
                break
            }

            // Reduce quality by 5%
            quality -= 0.05
        }

        // If we still don't have data or it's still too large, return the last attempt
        return compressedData ?? image.jpegData(compressionQuality: minQuality)
    }

    /// Compress multiple images
    /// - Parameter images: Array of UIImages to compress
    /// - Returns: Array of compressed image data
    static func compressImages(_ images: [UIImage]) -> [Data] {
        return images.compactMap { compressImage($0) }
    }
}
