import Foundation

extension NSSize {

    /// Scales the current size to fit within the target size while maintaining the aspect ratio.
    /// - Parameter targetSize: The size to fit into.
    /// - Returns: A new `NSSize` that fits within the `targetSize`.
    func scaledToFit(in targetSize: NSSize) -> NSSize {
        guard self.width > 0 && self.height > 0 else {
            return .zero // Avoid division by zero if the size is invalid.
        }
        
        let widthScale = targetSize.width / self.width
        let heightScale = targetSize.height / self.height
        
        let scale = min(widthScale, heightScale)
        
        return NSSize(width: self.width * scale, height: self.height * scale)
    }

    func scaledDown(to desiredWidth: CGFloat) -> NSSize {
        if width == desiredWidth {
            return self
        }

        if width < desiredWidth {
            // Don't scale larger
            return self
        }

        let height = (height * desiredWidth / width).rounded(.down)
        return NSSize(width: desiredWidth, height: height)
    }
}

extension NSSize {

    var ratio: CGFloat {
        guard height != 0 else {
            return 0
        }
        return width / height
    }
}
