<?php

namespace App\Jobs;

use Carbon\Carbon;
use Illuminate\Bus\Queueable;
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 Illuminate\Support\Facades\Storage;
use League\Flysystem\UnableToMoveFile;

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 Received name, stored in Storage::disk('local'), ie: storage/app
	 * @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 'jobname':
				return sprintf('%s %s',$this->do?->name,$this->file);

			default:
				return NULL;
		}
	}

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle()
	{
		$fs = Storage::disk(config('fido.local_disk'));
		$rel_name = sprintf('%s/%s',config('fido.dir'),$this->file);

		$to = new Tic;

		try {
			$fo = $to->load($this->file);

		} catch (\Exception $e) {
			Log::error(sprintf('%s:! Error loading TIC file [%s] (%s)',self::LOGKEY,$rel_name,$e->getMessage()));

			return;
		}

		$fo->save();

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

		if (config('fido.packet_keep')) {
			$dir = sprintf('%s/%s/%s/%s',config('fido.dir'),($x=Carbon::now())->format('Y'),$x->format('m'),$x->format('d'));
			Log::debug(sprintf('%s:- Moving processed TIC [%s] to [%s]',self::LOGKEY,$rel_name,$dir));

			try {
				if ($fs->makeDirectory($dir)) {
					$fs->move($rel_name,$x=sprintf('%s/%s',$dir,$this->file));
					Log::info(sprintf('%s:- Moved processed TIC [%s] to [%s]',self::LOGKEY,$rel_name,$x));

				} else
					Log::error(sprintf('%s:! Unable to create dir [%s]',self::LOGKEY,$dir));

			} catch (UnableToMoveFile $e) {
				Log::error(sprintf('%s:! Unable to move TIC [%s] to [%s] (%s)',self::LOGKEY,$rel_name,$dir,$e->getMessage()));

			} catch (\Exception $e) {
				Log::error(sprintf('%s:! Failed moving TIC [%s] to [%s] (%s)',self::LOGKEY,$rel_name,$dir,$e->getMessage()));
			}

		} else {
			if (! $fs->delete($rel_name))
				Log::alert(sprintf('%s:! Failed to delete [%s]',self::LOGKEY,$rel_name));
		}

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