# typed: strict
module IpAddressHelper
  extend T::Sig

  # Formats an IPAddr object to display properly with CIDR notation if it's a subnet
  # @param ip_addr [IPAddr, nil] The IP address object to format or nil
  # @return [String] A formatted string representation of the IP address
  sig { params(ip_addr: T.nilable(IPAddr)).returns(String) }
  def format_ip_address(ip_addr)
    if ip_addr.nil?
      ""
    else
      # For IPv4, check if the prefix is not 32 (full mask)
      # For IPv6, check if the prefix is not 128 (full mask)
      if (ip_addr.ipv4? && ip_addr.prefix < 32) ||
           (ip_addr.ipv6? && ip_addr.prefix < 128)
        # This is a CIDR range
        "#{ip_addr.to_s}/#{ip_addr.prefix}"
      else
        # Single IP address
        ip_addr.to_s
      end
    end
  end

  # Determines if the provided IP address is a CIDR range
  # @param ip_addr [IPAddr, nil] The IP address to check or nil
  # @return [Boolean] true if the address is a CIDR range, false otherwise
  sig { params(ip_addr: T.nilable(IPAddr)).returns(T::Boolean) }
  def cidr_range?(ip_addr)
    return false if ip_addr.nil?

    format_ip_address(ip_addr).include?("/")
  end
end
