class Buyers::LogRequestsController < Buyers::BaseController
  include ThreeScale::Search::Helpers
  include CubertLogsVisibility

  before_action :authorize_log_requests

  before_action :find_buyer
  before_action :find_cinstance
  before_action :find_service, only: [:index]

  activate_menu :buyers

  def index
    if provider_can_use_cubert_request_logs?
      logs_service   = CubertRequestLogsService.new(@service.cubert_info)
      @search        = ThreeScale::RequestLogsSearch.new(**cubert_params)
      @log_requests  = logs_service.get_list(@search.to_hash, pagination_params.merge(sort: sort_params))

      render action: 'cubert_logs'
    else
      @log_requests = @cinstance.backend_object.log_requests
    end
  end

  def purge
    @cinstance.backend_object.delete_all_log_requests

    respond_to do |format|
      format.html do
        flash[:notice] = 'All requests logs were purged.'
        redirect_to(admin_buyers_account_application_log_requests_url(@account,@cinstance))
      end

      format.js
    end

  end

  protected

  def authorize_log_requests
    authorize! :manage, :log_requests
  end

  def find_buyer
    @account = current_account.buyers.find(params[:account_id])
  end

  def find_cinstance
    @cinstance = @account.bought_cinstances.find(params[:application_id])
  end

  def find_service
    @service ||= @cinstance.service
  end

  def cubert_params
    { application_id: @cinstance.application_id }.merge(params[:search] || {}).symbolize_keys
  end

  def search_params
    params.fetch(:search, {}).permit(:code, { :timestamp => [:$lt, :$lte, :$gt, :$gte]}).symbolize_keys
  end

  def sort_params
    sort_column ? { sort_column => sort_direction } : { "timestamp" => "desc" }
  end

end
