module Measurement
  extend ActiveSupport::Concern

  included do
    around_action :measure_request
  end

  def measure_request
    start_time = Time.now
    yield
    end_time = Time.now

    metric_name = generate_metric_name

    duration = (end_time - start_time) * 1000
    Rails.logger.debug("metric_name:#{metric_name} duration:#{duration}")
    # we used to send this to statsd - noop until we replace this with a call to another stat aggregation service
  end

  def generate_metric_name
    path_components = request.path.split('/')

    if path_components.empty?
      prefix = 'admin-panel'
    else
      service = path_components[1]
      page = path_components[2..-1].join('_')
      prefix = "#{service}.#{page}"
    end

    "#{prefix}.#{action_name}.#{request.method}.#{response.status}"
  end
end
