class PasswordResetsController < ApplicationController
  skip_before_action :require_login
  skip_after_action :verify_authorized

  before_action :set_user, only: [:edit, :update]

  def new
  end

  def create
    @user = find_user_by_email

    if @user
      UserMailer.password_reset(@user).deliver_later
    end

    redirect_to new_session_path, notice: t(".notice")
  end

  def edit
    redirect_to new_session_path, notice: t(".notice") if @user.nil?
  end

  def update
    if @user && reset_password(@user, new_password_param)
      @user.regenerate_password_reset_token
      redirect_to new_session_path, notice: t(".notice")
    end
  rescue ActiveRecord::RecordInvalid
    flash.alert = t(".alert")
    render :edit
  end

  private

  def set_user
    @user = find_user_by_token
  end

  def password_reset_params
    params.require(:password_reset).permit(:email, :password)
  end

  def email_param
    password_reset_params.dig(:email)
  end

  def new_password_param
    password_reset_params.dig(:password)
  end

  def find_user_by_email
    @user = User.find_by(email: email_param)
  end

  def find_user_by_token
    @user = User.find_by(password_reset_token: params[:id])
  end
end
