<?php

namespace App\Check;

use App\Helpers\VulnerabilityScannerApiUtilsFacade as ApiUtils;
use Spatie\Health\Checks\Check;
use Spatie\Health\Checks\Result;

// See: https://spatie.be/docs/laravel-health/v1/basic-usage/creating-custom-checks
class VulnerabilityScannerApiCheck extends Check
{
    protected int $timeout = 5;

    protected int $retryTimes = 2;

    public function timeout(int $seconds): self
    {
        $this->timeout = $seconds;

        return $this;
    }

    public function retryTimes(int $times): self
    {
        $this->retryTimes = $times;

        return $this;
    }

    public function run(): Result
    {
        if (!$this->checkExternalIps()) {
            return Result::make()
                ->failed('External IPs unreachable');
        }
        if (!$this->checkHelloMongo()) {
            return Result::make()
                ->failed('Hello Mongo unreachable');
        }

        return Result::make()
            ->ok()
            ->shortSummary('Reachable');
    }

    private function checkHelloMongo()
    {
        $response = ApiUtils::timeout($this->timeout)
            ->retryTimes($this->retryTimes)
            ->hello_mongo();

        return array_key_exists('Mongo', $response) && $response['Mongo'] == 'ok';
    }

    private function checkExternalIps()
    {
        $response = ApiUtils::timeout($this->timeout)
            ->retryTimes($this->retryTimes)
            ->external_ips();

        return array_key_exists('sentinel_external_ips', $response);
    }

    private function checkCelery()
    {
        $response = ApiUtils::timeout($this->timeout)
            ->retryTimes($this->retryTimes)
            ->celery();

        return array_key_exists('Hello', $response) && $response['Hello'] == 'Celery';
    }
}