NPC Stops Patrolling after target is out of distance

So recently I decided to make a horror game and made the NPC for it.

But… the issue is once the NPC reaches the waypoint it just stops and I do not know the issue…

Here’s the code for the NPC.

local NPC = script.Parent
local Humanoid = NPC:WaitForChild(“Humanoid”)
NPC.PrimaryPart:SetNetworkOwner(nil)


local PathfindingService = game:GetService(“PathfindingService”)


local function getPath(destination)
local PathParams = {
[“AgentRadius”] = 5,
[“AgentHeight”] = 2,
[“AgentCanJump”] = false,
[“AgentCanClimb”] = false,
[“WaypointSpacing”] = math.huge,
Costs = {
–Climb = 2,
–NPCBarrier = math.huge
}
}

local path = PathfindingService:CreatePath(PathParams)

path:ComputeAsync(NPC.HumanoidRootPart.Position,destination.Position)

return path

end

local function findTarget()
local Players = game:GetService(“Players”)
local maxDistance = 23
local nearestTarget
– – –
for index, player in pairs(Players:GetPlayers()) do
if player.Character then
local target = player.Character
local distance = (NPC.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
– – –
if distance < maxDistance then
nearestTarget = target
maxDistance = distance
end
end
end
return nearestTarget
end

local function Chase(target)
local distance = (NPC.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude

if distance > 0 then
	Humanoid:MoveTo(target.HumanoidRootPart.Position)
else
	target.Humanoid.Health = 0
end

end

local function NPCWalk(destination)
local path = getPath(destination)

if path.Status == Enum.PathStatus.Success then 
for index, maindest in pairs(path:GetWaypoints()) do
	local target = findTarget()
	if target then
		print("TARGET FOUND.",target.Name)
		Chase(target)
		break
	else
		print("Moving to... ",maindest)
		repeat
			Humanoid:MoveTo(maindest.Position)
		until Humanoid.MoveToFinished:Wait()
		if maindest.Action == Enum.PathWaypointAction.Jump then
			Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
				print(NPC.Name.." Jumped.")
			if path.Blocked then
					Humanoid:MoveTo(NPC.HumanoidRootPart.Position * Vector3.new(1,1,1)) -- Fixes the path from being blocked.
				end
			end
			print("i suck at coding")
		end
	end
end

end

local function PatrolWaypoints(Waypoints)
while true do wait(0.001)
local PathWaypoints = Waypoints:GetChildren()
– – –
local RandomPoint = PathWaypoints[math.random(1,#PathWaypoints)]
– – –
NPCWalk(RandomPoint)
end
end

PatrolWaypoints(workspace:WaitForChild(“Waypoints”))

if anyone could help I’d appreciate it a lot.