class Provider::PasswordsController < FrontendController

  skip_before_action :login_required
  before_action :find_provider
  before_action :find_user, :only => [:show, :update]


  def destroy
    if user = @provider.users.find_by_email(email)
      user.generate_lost_password_token!
      flash[:notice] = "A password reset link has been emailed to you."
      redirect_to provider_login_path
    else
      flash[:error] = 'Email not found.'
      redirect_to provider_login_path(:request_password_reset => true)
    end
  end

  def show
  end

  def update
    user = params[:user]
    if @user.update_password(user[:password], user[:password_confirmation] )
      flash[:notice] = "The password has been changed."
      @user.kill_user_sessions
      redirect_to provider_login_path
    else
      render :action => 'show'
    end
  end

  private

  # Can't be used for neither Buyer nor Master
  #
  def find_provider
    unless @provider ||= Account.providers.find_by_self_domain(request.host.to_s)
      render_error "Wrong domain '#{request.host}' for path '#{request.path}'", status: 404
      false
    end
  end

  def find_user
    @user = @provider.find_user_by_lost_password_token(password_reset_token)
    unless @user
      flash[:error] = 'The password reset token is invalid.'
      redirect_to provider_login_path
    end
  end

  def email
    params.fetch(:email).to_s
  end

  def password_reset_token
    params.fetch(:password_reset_token).to_s
  end
end
