class ReleaseCollection
  def initialize(api_client:)
    @api_client = api_client
  end

  def current
    all.last
  end

  def previous
    all[-2]
  end

  def at(release)
    all.find { |m| m['title'] == release }
  end

  # Returns a list of release milestones, sorted in ascending order by start
  # date and ending with the one currently in development.
  #
  # Can be traversed using the array methods; such as #[] and #last. For
  # example, if the milestone in progress is %16.4:
  #   `all[-1]` will return the %16.4 milestone.
  #   `all.last` will return the %16.4 milestone.
  #   `all[-2]` will return the %16.3 milestone.
  #   `all[0]` will return the earliest milestone in the set (e.g. %15.5)
  def all
    @all ||= begin
      today = Time.now.strftime('%Y-%m-%d')
      api_client.get('groups/gitlab-org/milestones?state=active')
                .select { |milestone| milestone['start_date'] && milestone['start_date'] < today }
                .select { |milestone| /\A\d+\.\d+\z/.match?(milestone['title']) }
                .sort_by { |x| x['start_date'] }
    end
  end

  private

  attr_reader :api_client
end
