#!/usr/bin/env ruby
# relay — deliver webhook payloads and report on outcomes.
#
#   relay send <url> <json-payload>
#   relay report

require_relative "../lib/relay"

config = Relay::Config.load
abort(config.error) if config.err?
config = config.value

log = Relay::Log.new(config.log_path)

case ARGV[0]
when "send"
  url, raw = ARGV[1], ARGV[2]
  abort("usage: relay send <url> <json-payload>") unless url && raw
  delivery = Relay::Delivery.new(log: log, dead_letter_path: config.dead_letter_path)
  queue = Relay::Queue.new(delivery: delivery)
  queue.enqueue(url, JSON.parse(raw))
  result = queue.drain
  abort(result.error) if result.err?
when "report"
  reports = Relay::Reports.new(dead_letter_path: config.dead_letter_path)
  result = reports.render
  abort(result.error) if result.err?
  puts result.value
else
  abort("usage: relay <send|report>")
end
