<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use App\Classes\FTN\Packet;
use App\Jobs\PacketProcess as Job;
use App\Models\Address;

/**
 * Things to test
 * + Packet
 *   - Sender doesnt exist (try and send a bounce message in the same session)
 *   - Sender defined in DB by not ours
 *   - Sender has wrong password
 *   - Packet too old
 *
 * + Echomail
 *   - Area doesnt exist (to uplink)
 *   - Sender not subscribed (to uplink)
 *   - Sender cannot post (to uplink)
 *   - Sender has wrong address for echorea domain (to uplink)
 *   - Test message in echoarea
 *   - Echomail from address doesnt match packet envelope (to uplink)
 *   - Echomail too old (to uplink)
 *   - Rescanned dont generate notifications
 *   - Rescanned dont trigger bots
 *   - Some Notifications to an uplink should go to the admin instead?
 *
 * + Netmail
 *   - To hub, and user not defined (reject)
 *   - To hub, but user redirect (redirected)
 *   - To areafix (processed)
 *   - To ping (respond)
 *   - With trace turned on (respond)
 */
class PacketProcess extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'packet:process'
		.' {file : Packet to process}'
		.' {--N|nobot : Dont process bots}'
		.' {ftn? : System the packet is from}'
		.' {--Q|dontqueue : Dont queue the message}';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Process Packet';

	/**
	 * Execute the console command.
	 *
	 * @return int
	 * @throws \Exception
	 */
	public function handle(): int
	{
		$rel_name = sprintf('%s/%s',config('fido.dir'),$this->argument('file'));

		$m = [];
		if ($this->argument('ftn')) {
			$ao = Address::findFTN($this->argument('ftn'));

		} elseif (preg_match(sprintf('/^%s\.(.{3})$/',Packet::regex),$this->argument('file'),$m)) {
			$ao = Address::findOrFail(hexdec($m[1]));

		} else {
			$this->error('Unable to determine sender FTN address');

			return self::FAILURE;
		}

		Job::dispatchSync($rel_name,$ao->zone->domain,$this->option('dontqueue'));

		return self::SUCCESS;
	}
}