<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

use App\Classes\FTN\Tic;
use App\Models\Domain;

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

	private const LOGKEY = 'JTP';

	private ?Domain $do;

	public const QUEUE = 'tic';

	/**
	 * Create a new job instance.
	 *
	 * @param string $file
	 * @param string|null $domain
	 */
	public function __construct(private string $file,private ?string $domain=NULL)
	{
		$this->do = $domain ? Domain::where('name',$domain)->singleOrFail() : NULL;

		$this->onQueue(self::QUEUE);
	}

	public function __get($key): mixed
	{
		switch ($key) {
			case 'subject':
				return sprintf('%s %s',$this->do?->name,$this->file);

			default:
				return NULL;
		}
	}

	/**
	 * Execute the job.
	 *
	 * @return void
	 * @throws FileNotFoundException
	 */
	public function handle()
	{
		$to = new Tic;
		$to->load($this->file);

		Log::info(sprintf('%s:Processed [%s] storing [%s] as id [%d]',self::LOGKEY,$this->file,$to->fo->file,$to->fo->id));

		unlink($this->file);

		if ($to->isNodelist())
			NodelistImport::dispatch($to->fo,$this->domain);
	}
}