# frozen_string_literal: true

# GET data from coverartarchive.org
class CoverArtArchiveApi
  delegate_missing_to :import_request

  def self.get(**args)
    new(**args).get
  end

  def initialize(import_order:, uri:)
    @import_order = import_order
    @uri          = uri
  end

  attr_reader :import_order, :uri

  def get
    run!
    response = connection.get(uri)
  rescue StandardError => e
    Rails.logger.error("#{e} #{response&.body}")
    failure!
    raise
  else
    done!
    response
  end

  private

  def connection
    @connection ||= Faraday.new do |connection|
      connection.use Faraday::Response::RaiseError
      connection.use FaradayMiddleware::FollowRedirects, limit: 5
      connection.use ImportMiddleware, import_request: import_request
      connection.request :retry, retry_options
      connection.adapter Faraday.default_adapter
    end
  end

  def import_request
    @import_request ||= import_order.import_requests.create!(uri: uri)
  end

  def retry_options
    { max: 5, interval: 0.1, interval_randomness: 0.5, backoff_factor: 2 }
  end
end
