class InvitationsController < ApplicationController
  def show
    @user = User.find_by_valid_invitation_token(params[:token])

    if @user.nil?
      redirect_to root_path, alert: "Invalid or expired invitation link."
    end
  end

  def update
    @user = User.find_by_valid_invitation_token(params[:token])

    if @user.nil?
      redirect_to root_path, alert: "Invalid or expired invitation link."
      return
    end

    if @user.update(invitation_params)
      @user.update(
        invitation_accepted_at: Time.current,
        invitation_token: nil
      )

      session[:user_id] = @user.id
      redirect_to admin? ? admin_root_path : root_path, notice: "Welcome to Sanasto Wiki, #{@user.name}!"
    else
      render :show, status: :unprocessable_entity
    end
  end

  private

  def invitation_params
    params.require(:user).permit(:password, :password_confirmation)
  end
end
