require_relative "result"

module Relay
  # Renders report rows for terminal output.
  class Formatter
    HEADERS = %w[url attempts outcome].freeze

    def render(rows)
      return Result.err("no rows") if rows.empty?

      widths = column_widths(rows)
      lines = [format_row(HEADERS, widths)]
      lines += rows.map { |row| format_row(row, widths) }
      Result.ok(lines.join("\n"))
    end

    private

    def column_widths(rows)
      ([HEADERS] + rows).transpose.map { |col| col.map { |c| c.to_s.length }.max }
    end

    def format_row(row, widths)
      row.zip(widths).map { |cell, w| cell.to_s.ljust(w) }.join("  ")
    end
  end
end
