<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

use App\Classes\FTN\Message;
use App\Models\Setup;

class ProcessPacket implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	private Message $msg;

	public function __construct(Message $msg)
	{
		// Some checks
		$this->msg = $msg;
	}

	/**
	 * When calling ProcessPacket - we assume that the packet is from a valid source
	 */
	public function handle()
	{
		// Load our details
		$ftns = Setup::findOrFail(config('app.id'))->system->addresses;

		// If we are a netmail
		if ($this->msg->isNetmail()) {
			// @todo Enable checks to reject old messages

			// Determine if the message is to this system, or in transit
			if ($ftns->search(function($item) { return $this->msg->tftn == $item->ftn; }) !== FALSE) {
				// @todo Check if it is a duplicate message
				// @todo Check if the message is from a system we know about

				$processed = FALSE;

				// If the message is to a bot, we'll process it
				foreach (config('process.robots') as $class) {
					if ($processed = $class::handle($this->msg)) {
						break;
					}
				}

				// If not processed, no users here!
				if (! $processed) {
					dump('message not processed, no users here');
				}

			// If in transit, store for collection
			} else {
				// @todo Check if the message is to a system we know about
				// @todo In transit loop checking
				// @todo In transit TRACE response

				dump('netmail in transit');
			}

		// Else we are echomail
		} else {
			dump('echomail');
			// Determine if we know about this echo area
			// Can the sender create it if it doesnt exist?
			// Create it, or

			// Else record in bad area

			// We know about this area, store it
		}
	}
}