module History
  class DeletionsController < BaseController
    def index
      authorize Deletion

      search = params.fetch(:search, {:requester => ""}).permit(:requester)

      # List Deletions
      begin
        results = Deletion.list_scheduled_deletions(search)
      rescue StandardError => e
        flash[:error] = e.message
        redirect_to history_deletions_path
        return
      end
      @deletions = results[:items]

      # Confirmation Module
      @user_id = params.fetch(:search, {:user_id => ""}).permit(:user_id)[:user_id]
      unless @user_id.blank?
        begin
          results = Deletion.get_user_stats(@user_id)
          if results[:data] < 1
            raise StandardError, "There is no data associated with user #{@user_id}"
          end
        rescue StandardError => e
          flash[:error] = e.message
          redirect_to history_deletions_path
          return
        end
        @user_rows = results[:data]
        @deletion_time = to_date_time(params.fetch(:deletion_time, ""))
      end
    end

    def to_date_time(time)
      if time == "3_years"
        return DateTime.now.next_year(3).to_time # rubocop:disable Style/DateTime
      elsif time == "24_hours"
        return DateTime.now.next_day(1) # rubocop:disable Style/DateTime
      else
        return nil
      end
    end

    def create
      authorize Deletion

      if params[:deletion_time].blank?
        flash[:error] = "Deletion Time required"
        redirect_to history_deletions_path
        return
      end

      user_id = params[:user_id]
      requester = current_user.ldap_login

      begin
        deletion_time = time_to_protobuf_timestamp(params[:deletion_time])
        Deletion.request_deletion(
          user_id.to_s,
          requester.to_s,
          deletion_time
        )
      rescue StandardError => e
        flash[:error] = e.message
        redirect_to history_deletions_path
        return
      end

      delete_req = Deletion.new
      delete_req.user_id = user_id.to_s
      delete_req.requester = requester.to_s
      delete_req.deletion_time = params[:deletion_time]
      delete_user_audits(delete_req)
      flash[:success] = "Successfully requested deletion"

      redirect_to history_deletions_path
    end

    private

    def time_to_protobuf_timestamp(time_str)
      parsed_time = Time.parse(time_str)

      Google::Protobuf::Timestamp.new(seconds: parsed_time.to_i)
    end

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

  end
end
