<?php

declare(strict_types=1);

namespace PpPhp\Core\Licensing;

/**
 * A shipped, known-current CA trust anchor for the platform's OWN outbound HTTPS
 * (licence activation/check-in, advisory pulls, auto-update checks) to the licence
 * authority and update servers.
 *
 * WHY: a very common cause of "could not reach the licence service" on budget /
 * infrequently-patched hosts is an OUT-OF-DATE SYSTEM CA STORE that cannot validate
 * the authority's (Let's Encrypt) certificate chain — the TLS handshake then fails
 * fast. Callers try the system store first and, only if that fails with a TLS-trust
 * error, retry once against this bundle. It is NOT a security downgrade: the peer
 * certificate is still fully verified, just against a trust anchor we know is current.
 *
 * The bundle carries the ISRG roots (ISRG Root X1 + X2) that Let's Encrypt chains to;
 * everything above them is served in the TLS handshake itself.
 */
final class CaBundle
{
    /** Absolute path to the shipped bundle, or '' if it isn't present in this copy. */
    public static function path(): string
    {
        $p = __DIR__ . '/ca/isrg-roots.pem';
        return is_file($p) ? $p : '';
    }

    /** True when a curl error string looks like a TLS / CA trust-store failure. */
    public static function isTlsTrustError(string $err): bool
    {
        if ($err === '') {
            return false;
        }
        $e = strtolower($err);
        foreach (['ssl', 'certificate', 'ca cert', 'cafile', 'self-signed', 'self signed', 'unable to get local issuer'] as $needle) {
            if (str_contains($e, $needle)) {
                return true;
            }
        }
        return false;
    }
}
