<?php

namespace idoit\Module\SyneticsJdisc\Service;

use idoit\Module\SyneticsJdisc\SSLCertificateException;
use isys_application;
use isys_component_template_language_manager;

class CertificateChecker
{
    /**
     * Validates and checks the SSL certificate of the JDisc server
     * Ensures all required connection parameters are present and the SSL certificate is valid
     *
     * @param array $server JDisc server configuration array
     * @param isys_component_template_language_manager $language
     * @return void
     * @throws SSLCertificateException When SSL certificate validation fails
     * @throws \Exception When required server configuration is missing
     */
    public static function checkCertificate(array $server, isys_component_template_language_manager $language): void
    {
        $requiredFields = [
            'discovery_protocol',
            'host',
            'discovery_port',
        ];

        foreach ($requiredFields as $field) {
            if (empty($server[$field])) {
                throw new \Exception($language->get('LC__REPORT__VIEW__JDISC_AVAILABILITY__NO_GRAPHQL'));
            }
        }

        $httpClient = isys_application::instance()->container->get('http_client')->getClient();
        try {
            $httpClient->request(
                'GET',
                sprintf(
                    '%s://%s:%s',
                    $server['discovery_protocol'],
                    $server['host'],
                    $server['discovery_port']
                ),
                ['verify' => true]
            );
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            throw new SSLCertificateException($e->getHandlerContext()['error']);
        }
    }
}
