require "json"
require_relative "result"
require_relative "delivery"
require_relative "formatter"

module Relay
  # Summarizes delivery outcomes for the `relay report` command, including
  # entries the Delivery dead-letter path wrote out.
  class Reports
    def initialize(dead_letter_path:, formatter: Formatter.new)
      @dead_letter_path = dead_letter_path
      @formatter = formatter
    end

    def failed_deliveries
      return Result.ok([]) unless File.exist?(@dead_letter_path)

      entries = File.readlines(@dead_letter_path).map { |line| JSON.parse(line) }
      Result.ok(entries)
    rescue JSON::ParserError => e
      Result.err("dead-letter file corrupt: #{e.message}")
    end

    def render
      failures = failed_deliveries
      return failures if failures.err?

      rows = failures.value.map do |entry|
        [entry["url"], Delivery.attempt_budget, "dead-lettered"]
      end
      rows.empty? ? Result.ok("no failed deliveries") : @formatter.render(rows)
    end
  end
end
