<?php

declare(strict_types=1);

namespace PpPhp\Core\Update;

use PpPhp\Core\Licensing\LicenseKeys;

/**
 * Builds and Ed25519-signs the advisory feed the authority hands a client on an
 * authenticated check-in. Authority-only — it needs the vendor SECRET key, which
 * never ships to a client. The client verifies the token with the pinned PUBLIC
 * key (see AdvisoryClient), exactly as it verifies a release feed or a licence
 * lease, so a mirror or man-in-the-middle can neither forge nor alter an advisory.
 */
final class AdvisoryFeed
{
    /**
     * A signed advisory token for one licensed installation, or '' when there is
     * nothing to say (no live advisories for it) or no signing key is present.
     *
     * @param array{0?:string,1?:string} $identity [instanceId, licenceKey] the
     *        caller authenticated as — used both to target and to stamp the feed
     *        so the recipient can confirm it was built for it.
     */
    public static function signedFor(array $identity, string $edition = 'client', ?int $now = null): string
    {
        try {
            $advisories = AdvisoryStore::visibleTo($identity, $edition);
            if ($advisories === []) return '';

            $keys = new LicenseKeys();
            if (!$keys->exists()) return '';

            $payload = [
                'advisories' => array_values($advisories),
                'iid'        => (string) ($identity[0] ?? ''),
                'iat'        => $now ?? time(),
            ];
            return UpdateProtocol::sign($payload, $keys->secretKey(), UpdateProtocol::ADVISORY_PREFIX);
        } catch (\Throwable $e) {
            return '';   // advisories are a nicety — never break a check-in
        }
    }
}
