require 'http.rb'
  
class WebhookWorker
  include Sidekiq::Worker
  sidekiq_options :queue => :webhook, :retry => 10, :backtrace => true, dead: false 

  sidekiq_retry_in do |retry_count|
    # Exponential backoff, with a random 30-second to 10-minute "jitter"
    # added in to help spread out any webhook "bursts."
    jitter = rand(30.seconds..10.minutes).to_i
 
    (retry_count ** 5) + jitter
  end

  def perform(webhook_event_id)
    webhook_event = WebhookEvent.find_by(id: webhook_event_id)
    return if
      webhook_event.nil?
   
    webhook_endpoint = webhook_event.webhook_endpoint
    return if webhook_endpoint.nil? || !webhook_endpoint.enabled?
    # Send the webhook request with a 30 second timeout.
    response = HTTP.headers(
                     'User-Agent' => 'WavespotWebhook/1.0',
                     'Content-Type' => 'application/json',
                   )
                   .post(
                     webhook_endpoint.url,
                     body: {
                       key: webhook_endpoint.shared_key,
                       event: webhook_event.event,
                       payload: webhook_event.payload,
                       test_event: webhook_event.is_test
                     }.to_json
                   )
    p "[WEBHOOK-EVENT-WORKER][#{webhook_event_id}] :: Resonse :: #{response.code} :: #{response.body.to_s}"
    # Store the webhook response.
    webhook_event.update(response: {
      headers: response.headers.to_h,
      code: response.code.to_i,
      body: response.body.to_s,
    })
   
    # Raise a failed request error and let Sidekiq handle retrying.
    # raise FailedRequestError unless
      # response.status.success?
    rescue HTTP::TimeoutError
    # This error means the webhook endpoint timed out. We can either
    # raise a failed request error to trigger a retry, or leave it
    # as-is and consider timeouts terminal. We'll do the latter.
    webhook_event.update(response: { error: 'TIMEOUT_ERROR' })
  end

end 
