module Public
  class PasswordResetsController < WebBaseController
    def new
    end

    def create
      user = User.find_by(email: params[:email]&.downcase&.strip)
      if user
        token = user.generate_password_reset!
        UserMailer.password_reset(user, token).deliver_now
      end

      redirect_to public_login_path,
                  notice: "Se l'email è registrata, riceverai a breve un link per reimpostare la password."
    end

    def edit
      @user = User.find_by_password_reset_token(params[:token])
      if @user.nil? || @user.password_reset_expired?
        redirect_to new_public_password_reset_path,
                    alert: "Link non valido o scaduto. Richiedi un nuovo reset password."
        return
      end
      @token = params[:token]
    end

    def update
      @user = User.find_by_password_reset_token(params[:token])
      if @user.nil? || @user.password_reset_expired?
        redirect_to new_public_password_reset_path,
                    alert: "Link non valido o scaduto. Richiedi un nuovo reset password."
        return
      end

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

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

      @user.update!(password: params[:password])
      @user.clear_password_reset!
      redirect_to public_login_path, notice: "Password aggiornata. Ora puoi accedere."
    end
  end
end
