module Debci
  OldestJob = Struct.new(:arch, :oldest_job) do
    def self.get
      if !@data || !@timestamp || Time.now > (@timestamp + 1.hour)
        @data = fetch
        @timestamp = Time.now
      end
      @data
    end

    def self.reset!
      @data = @timestamp = nil
    end

    def self.fetch
      query = <<-ENDQUERY
        SELECT arch, min(created_at) as oldest_job
        FROM jobs
        WHERE status IS NULL AND created_at > $1
        GROUP by arch;
      ENDQUERY

      a_month_ago = Time.now - 1.month
      results = ActiveRecord::Base.connection.exec_query(
        query,
        "Oldest job in the queue",
        [a_month_ago]
      )
      results.cast_values.map do |row|
        self.new(*row)
      end
    end
  end
end
