<?php

namespace App\Checklist;

use App\Contracts\GoLiveChecklist;
use Illuminate\Support\Str;
use Stancl\Tenancy\Contracts\Domain;

class CheckPrimaryDomain implements GoLiveChecklist
{
    /**
     * Name of the check
     *
     * @return string
     */
    public function name(): string
    {
        return __('go-live.primary_domain');
    }

    /**
     * Has the check passed
     *
     * @return bool|null
     */
    public function passes(): ?bool
    {
        return tenant()->domains()
            ->where('verified', 1)
            ->where('primary', 1)
            ->exists();
    }

    /**
     * URL to perform the check
     *
     * @return string
     */
    public function urlToCheck(): string
    {
        return route('tenant.checklists.domain', tenant()->domains()->where('primary', 1)->first()->id ?? 0);
    }

    /**
     * Perform verification
     *
     * @param Domain $domain
     * @return bool
     */
    public function performCheck(Domain $domain): bool
    {
        if (app()->environment('local') && Str::endsWith($domain->domain, '.localhost')) {
            $verified = true;
        } else {
            $verified = (int)in_array(gethostbyname($domain->domain), config('app.system_dns_ip'));
        }
        $domain->update([
            'verified' => $verified
        ]);
        return $verified;
    }
}
