# frozen_string_literal: true

class RunRepo < ROM::Repository[:runs]
  def by_pk(id)
    runs.by_pk(id).one
  end

  def by_test(test)
    runs.where(test_id: test.id).to_a
  end

  def by_target(location, url)
    runs.where(location: location, url: url)
  end

  def store(test, data, is_median)
    begin
      runs.command(:create).call test_id: test.id,
                                 run: data['run'],
                                 url: test.url,
                                 location: test.location,
                                 ran_at: data['date'],
                                 first_byte: data['TTFB'],
                                 dom_loading: data['domLoading'],
                                 title_time: data['titleTime'],
                                 first_paint: data['firstPaint'],
                                 render: data['render'],
                                 dom_interactive: data['domInteractive'],
                                 load_time: data['loadTime'],
                                 fully_loaded: data['fullyLoaded'],
                                 last_visual_change: data['lastVisualChange'],
                                 dom_elements: data['domElements'],
                                 bytes_out: data['bytesOut'],
                                 bytes_in: data['bytesIn'],
                                 connections: data['connections'],
                                 requests: data['requests'].count,
                                 responses_200: data['responses_200'],
                                 responses_404: data['responses_404'],
                                 responses_other: data['responses_other'],
                                 domain_names: data['domains'].count,
                                 is_median: is_median
    rescue ROM::SQL::UniqueConstraintError
      puts "Duplicate run found Test: #{test.id} Run: #{data['run']}."
    rescue ROM::SQL::NotNullConstraintError
      puts JSON.pretty_unparse(data)
      raise
    end
  end
end