module History
  class QueryAuditsController < History::BaseController
    before_action :verify_max_page, only: [:index]

    def index
      authorize QueryAudit

      options = params.fetch(:search, {})
      return if options.all? { |_k, v| v.blank? }

      options[:page] = params[:page]
      options.update(options) { |_k, v| v.downcase if v.is_a? String }
      @audits = History::QueryAudit.all(options)

      # inject geoIP data into audit objects
      #  containing embedded IPs
      History::QueryAudit.hydrate_audits_geo!(@audits)

      track_action! trackable_request
        .assemble_an
        .admin_panel_audits_search(
          created_after_utc:   options[:created_at_gte],
          created_before_utc:  options[:created_at_lte],
          audit_user_type:     options[:user_type],
          user_id:             options[:user_id],
          audit_action:        options[:action],
          audit_resource_type: options[:resource_type],
          audit_resource_id:   options[:resource_id],
          audit_attribute:     options[:attribute],
          audit_old_value:     options[:old_value],
          audit_new_value:     options[:new_value]
        )
    end

    private

    def verify_max_page
      if params[:page].to_i > History::QueryAudit::MAX_PAGE
        flash[:warning] = "Browsing over #{History::QueryAudit::MAX_PAGE} pages is currently not supported. Please refine your search terms for fewer results."
        return redirect_to(request.referrer) if request.referrer.present?
        return redirect_to(history_query_audits_path)
      end
    end
  end
end
