module History
  class ReportsController < BaseController
    def index
      authorize Report

      search = params.fetch(:search, {:requester => ""}).permit(:requester)
      begin
        results = Report.list_reports(search)
      rescue StandardError => e
        flash[:error] = e.message
        redirect_to history_reports_path
        return
      end
      @reports = results[:items]
    end

    def create
      authorize Report

      user_id = params.fetch(:search, {:user_id => ""})[:user_id]
      requester = current_user.ldap_login

      begin
        Report.request_report(
          user_id.to_s,
          requester.to_s
        )
      rescue StandardError => e
        flash[:error] = e.message
        redirect_to history_reports_path
        return
      end

      report_req = Report.new
      report_req.user_id = user_id.to_s
      report_req.requester = current_user.ldap_login
      report_req.status = "requested"
      report_req.request_time = Time.now

      audit_request_report(report_req)
      flash[:success] = "Successfully requested report"
      redirect_to history_reports_path
    end

    def audit_request_report(report_req)
      changesets = changeset(report_req)
      audit = Audit.new(
        action: "user_audit_report_request",
        user_type: "ldap_user",
        user_id: current_user.ldap_login,
        resource_id: report_req.user_id,
        changes: changesets
      )
      AddAudit.add(audit)
    end
  end
end
