<?php

declare(strict_types=1);

final class HexaGameCloudMtlsConfig
{
    public static function fromAddonSettings(array $vars): array
    {
        if (empty($vars['use_mtls'])) {
            return [];
        }

        return self::normalize([
            'cert' => (string) ($vars['mtls_cert_path'] ?? ''),
            'key' => (string) ($vars['mtls_key_path'] ?? ''),
            'ca' => (string) ($vars['mtls_ca_path'] ?? ''),
            'fingerprint' => (string) ($vars['mtls_cert_fingerprint'] ?? ''),
        ]);
    }

    public static function fromServerParams(array $params): array
    {
        if (empty($params['configoptions']['use_mtls']) && empty($params['configoption5'])) {
            return [];
        }

        return self::normalize([
            'cert' => (string) ($params['configoptions']['mtls_cert_path'] ?? $params['configoption5'] ?? ''),
            'key' => (string) ($params['configoptions']['mtls_key_path'] ?? $params['configoption6'] ?? ''),
            'ca' => (string) ($params['configoptions']['mtls_ca_path'] ?? $params['configoption7'] ?? ''),
            'fingerprint' => (string) ($params['configoptions']['mtls_cert_fingerprint'] ?? ''),
        ]);
    }

    public static function applyToCurl($ch, array $mtls): void
    {
        if ($mtls === []) {
            return;
        }

        if (!empty($mtls['cert']) && is_readable($mtls['cert'])) {
            curl_setopt($ch, CURLOPT_SSLCERT, $mtls['cert']);
        }

        if (!empty($mtls['key']) && is_readable($mtls['key'])) {
            curl_setopt($ch, CURLOPT_SSLKEY, $mtls['key']);
        }

        if (!empty($mtls['ca']) && is_readable($mtls['ca'])) {
            curl_setopt($ch, CURLOPT_CAINFO, $mtls['ca']);
        }
    }

    public static function fingerprintHeader(array $mtls): array
    {
        if (empty($mtls['fingerprint'])) {
            return [];
        }

        $fingerprint = strtolower(str_replace(':', '', $mtls['fingerprint']));
        return ['X-HGC-Client-Cert-Fingerprint: ' . $fingerprint];
    }

    private static function normalize(array $input): array
    {
        if ($input['cert'] === '' && $input['key'] === '' && $input['ca'] === '') {
            return [];
        }

        return $input;
    }
}
