class VendingMachine
  attr_reader :balance

  def initialize(items = nil)
    @inventory = []
    @balance = 0.0

    return unless items.is_a?(Array)

    items.each do |item|
      next unless item.is_a?(Hash)

      name = item[:name]
      price = item[:price]
      quantity = item[:quantity]

      next if name.nil? || (name.respond_to?(:strip) && name.strip.empty?)
      next unless price.is_a?(Numeric)

      qty = quantity.is_a?(Numeric) ? quantity.to_i : 0
      qty = 0 if qty < 0

      @inventory << { name: name.to_s, price: price.to_f, quantity: qty }
    end
  end

  def insert_money(amount)
    return unless amount.is_a?(Numeric)
    return unless amount > 0
    @balance = (@balance.to_f + amount.to_f)
  end

  def return_change
    change = @balance.to_f
    @balance = 0.0
    change
  end

  def select_item(name)
    return "Item not found" if name.nil? || (name.respond_to?(:empty?) && name.empty?)

    item = @inventory.find { |i| i[:name] == name }
    return "Item not found" if item.nil?
    return "Item out of stock" if item[:quantity].to_i <= 0

    price = item[:price].to_f
    return "Insufficient funds. Please insert more money." if @balance < price

    @balance = (@balance - price)
    item[:quantity] = item[:quantity].to_i - 1
    "Dispensed #{name}"
  end

  def check_stock(name)
    return 0 if name.nil?
    item = @inventory.find { |i| i[:name] == name }
    item ? item[:quantity].to_i : 0
  end

  def restock(name, quantity)
    return unless name.is_a?(String) && !name.strip.empty?
    return unless quantity.is_a?(Numeric) && quantity > 0

    qty = quantity.to_i
    stock = @inventory.find { |i| i[:name] == name }
    if stock
      stock[:quantity] = stock[:quantity].to_i + qty
    else
      @inventory << { name: name, price: 1.25, quantity: qty }
    end
    true
  end

  def get_available_items
    @inventory.select { |i| i[:quantity].to_i > 0 }
  end
end