<?php

namespace App\Jobs;

use Carbon\Carbon;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
use Repat\LaravelJobs\Job;

use App\Models\Address;

class SystemHeartbeat #implements ShouldQueue
{
	use Dispatchable;

	private const LOGKEY = 'JSH';

	/**
	 * @param bool $force Include systems that are autohold
	 */
	public function __construct(private ?bool $force=NULL) {}

	/**
	 * Execute the job.
	 */
	public function handle(): void
	{
		// Find our uplinks that are hubs, NC, RC or ZCs
		// Find any system that also has heartbeat configured
		$l = our_nodes()
			->filter(fn($item)=>$item->heartbeat || ($item->role_id < Address::NODE_NN))
			->filter(fn($item)=>$this->force || (! $item->autohold))
			->unique(fn($item)=>$item->system_id);

		// If we havent polled in heatbeat hours, poll system
		foreach ($l as $oo) {
			if (Job::where('queue','poll')->get()->pluck('command.address.id')->search($oo->id) === FALSE) {
				if ((! $oo->system->last_seen)
					|| ($oo->system->hearbeat && ($oo->system->last_seen->addHours($oo->system->heartbeat) < Carbon::now()))
					|| ((! $oo->system->hearbeat) && ($oo->role_id < Address::NODE_NN) && ($oo->system->last_seen->addHours(6) < Carbon::now())))
				{
					Log::info(sprintf('%s:- Polling [%s] (%s) - we havent seen them since [%s], heartbeat [%d]',
						self::LOGKEY,
						$oo->ftn,
						$oo->system->name,
						$oo->system->last_seen ?: 'Never',
						$oo->system->heartbeat,
					));

					AddressPoll::dispatch($oo);

				} else {
					Log::debug(sprintf('%s:= Not scheduling poll to [%s], we saw them [%s], heartbeat [%d]',
						self::LOGKEY,
						$oo->ftn,
						$oo->system->last_seen,
						$oo->system->heartbeat
					));
				}

			} else {
				Log::notice(sprintf('%s:= Not scheduling poll to [%s], there is already one in the queue',self::LOGKEY,$oo->ftn));
			}
		}
	}
}