<?php

namespace App\Jobs;

use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;

use App\Classes\FTN\Message;
use App\Models\{Address,Domain,System};
use App\Notifications\Echomails\AbsentNodes;
use App\Notifications\Emails\NodeMarkedDown as NodeMarkedDownEmail;
use App\Notifications\Netmails\NodeMarkedDown as NodeMarkedDownNetmail;
use App\Notifications\Emails\NodeMarkedHold as NodeMarkedHoldEmail;
use App\Notifications\Netmails\NodeMarkedHold as NodeMarkedHoldNetmail;
use App\Notifications\Emails\NodeDelisted as NodeDelistedEmail;
use App\Notifications\Netmails\NodeDelisted as NodeDelistedNetmail;

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

	private const LOGKEY = 'JAC';

	private Address $ao;	// System address

	/**
	 * Create a new job instance.
	 */
	public function __construct(Address $ao)
	{
		$this->ao = $ao->withoutRelations();
	}

	/**
	 * Execute the job.
	 */
	public function handle(): void
	{
		// Remove echomail not collected from echomail_seenby
		DB::table('echomail_seenby')
			->where('address_id',$this->ao->id)
			->whereNotNull('export_at')
			->whereNull('sent_at')
			->delete();

		// Remove FLAG_INTRANSIT from netmail that hasnt been delivered
		DB::table('netmails')
			->where('tftn_id',$this->ao->id)
			->whereRaw(sprintf('(flags & %d) > 0',Message::FLAG_INTRANSIT))
			->update(['flags'=>DB::raw(sprintf('(flags & ~%d)',Message::FLAG_INTRANSIT))]);

		// Remove files not collected
		DB::table('file_seenby')
			->where('address_id',$this->ao->id)
			->whereNotNull('export_at')
			->whereNull('sent_at')
			->delete();
	}
}