import UIKit

enum ImageResize {
    /// Resizes a JPEG/PNG so its longest edge is at most `maxDimension`,
    /// then re-encodes as JPEG with the given quality. Returns the original
    /// data if it can't be decoded.
    static func resizedJPEG(
        from data: Data,
        maxDimension: CGFloat = 2048,
        quality: CGFloat = 0.8
    ) -> Data {
        guard let image = UIImage(data: data) else { return data }
        let longest = max(image.size.width, image.size.height)
        guard longest > maxDimension else {
            // already small enough — just re-encode to JPEG
            return image.jpegData(compressionQuality: quality) ?? data
        }
        let scale = maxDimension / longest
        let target = CGSize(width: image.size.width * scale, height: image.size.height * scale)
        let renderer = UIGraphicsImageRenderer(size: target, format: {
            let f = UIGraphicsImageRendererFormat.default()
            f.scale = 1
            f.opaque = true
            return f
        }())
        let resized = renderer.image { _ in
            image.draw(in: CGRect(origin: .zero, size: target))
        }
        return resized.jpegData(compressionQuality: quality) ?? data
    }
}
