module Admin
  class PasswordsController < Admin::BaseController
    def edit
    end

    def update
      unless current_admin_account.authenticate(params[:current_password])
        flash.now[:alert] = "Password attuale non corretta"
        return render :edit, status: :unprocessable_entity
      end

      if params[:password].blank? || params[:password].length < 8
        flash.now[:alert] = "La nuova password deve avere almeno 8 caratteri"
        return render :edit, status: :unprocessable_entity
      end

      if params[:password] != params[:password_confirmation]
        flash.now[:alert] = "Le password non coincidono"
        return render :edit, status: :unprocessable_entity
      end

      if current_admin_account.update(password: params[:password])
        redirect_to admin_root_path, notice: "Password aggiornata"
      else
        flash.now[:alert] = current_admin_account.errors.full_messages.to_sentence
        render :edit, status: :unprocessable_entity
      end
    end
  end
end
