<?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\Config;
use Illuminate\Support\Facades\Log;

use App\Models\{Site,Supplier,TLD};

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

	private const LOGKEY = 'JSD';

	protected Site $site;
	protected Supplier $supplier;
	protected bool $forceprod;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Site $site,Supplier $supplier,bool $forceprod=FALSE)
    {
        $this->site = $site;
		$this->supplier = $supplier;
		$this->forceprod = $forceprod;

		Config::set('site',$site);
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
		$registrar_id = ($x=$this->supplier->registrar()) ? $x->id : NULL;

		foreach ($this->supplier->API($this->forceprod)->getDomains(['fetchall'=>true]) as $domain) {
			// @todo See if we can find this domain by its ID

			// Find this domain by it's name
			if (! $to=TLD::domaintld($domain->domain_name)) {
				Log::alert(sprintf('%s:Domain [%s] from (%s) is not in a TLD that we manage',self::LOGKEY,$this->supplier->name,$domain->domain_name));

			} elseif (($domainpart=strtolower($to->domain_part($domain->domain_name))) && (($x=$to->domains->where('domain_name',$domainpart))->count() === 1)) {
				$o = $x->pop();
				$o->registrar_auth_password = $domain->auth_key;
				$o->expire_at = Carbon::create($domain->expiry_date);
				$o->registrar_account = $domain->account;
				$o->registrar_username = '';
				$o->registrar_ns = Supplier\Domain::nameserver_name($domain->nameservers());
				if ($registrar_id)
					$o->domain_registrar_id = $registrar_id;

				if ($o->getDirty()) {
					Log::info(sprintf('%s:Updating Domain [%s] from (%s)',self::LOGKEY,$domain->domain_name,$this->supplier->name));
					$o->save();

				} else {
					Log::info(sprintf('%s:No Change to Domain [%s] from (%s)',self::LOGKEY,$domain->domain_name,$this->supplier->name));
				}

			// Alert an unmanaged name.
			} else {
				Log::alert(sprintf('%s:Domain [%s] from (%s) is not one managed in OSB',self::LOGKEY,$this->supplier->name,$domain->domain_name));
			}
		}
    }
}