# frozen_string_literal: true

class TestRepo < ROM::Repository[:tests]
  commands :create, update: :by_pk

  def by_pk(id)
    tests.by_pk(id).one
  end

  def store(s3_obj, data)
    begin
      tests.command(:create).call id: data['id'],
                                  url: data['url'] || data['URL'],
                                  location: data['location'].split(':')[0],
                                  browser: data['location'].split(':')[1],
                                  bandwidth_down: data['bwDown'],
                                  bandwidth_up: data['bwUp'],
                                  latency: data['latency'],
                                  completed_at: data['completed'],
                                  json_url: "#{Indicina::CDN_DOMAIN}#{s3_obj.key}"

    rescue ROM::SQL::UniqueConstraintError
      puts "Duplicate test found: #{data['id']}"
    end
  end
end