require "csv"

module SupportTools
  class AccountRecoveryController < SupportTools::BaseController

    def index
      @job = SupportTools::AccountRecovery.new
      authorize @job
    end

    def create
      @job = SupportTools::AccountRecovery.new job_params

      rows = parse_csv
      @job.reporter = current_user.ldap_login
      @job.users = rows
      authorize @job
      @job.save

      if @job.errors.present?
        flash.now[:danger] = @job.errors.full_messages.to_sentence
        render :index
      else
        flash[:success] = "Successfully created job"
        redirect_to support_tools_account_recovery_index_path
      end

      unless @job.errors.present?
        track_action! trackable_request.assemble_an.admin_panel_support_tools_submit(action: "account_recovery")
      end
    end

    protected

    def job_params
      params.require(:file)
      params.permit(:file)
    end

    def parse_csv
      CSV.parse(params[:file].read).flatten(1)
    end
  end
end
