<?php

declare(strict_types=1);

namespace Drupal\flowdrop\Service\Bundle;

use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * Resolves trusted publisher keys from flowdrop_trusted_publisher entities.
 *
 * Returns a raw public key only for an enabled publisher whose stored key is
 * valid base64 of the correct length; anything else resolves to NULL so the
 * verifier reports the bundle untrusted rather than erroring.
 *
 * @internal
 */
final class TrustedPublisherResolver implements TrustedPublisherResolverInterface {

  public function __construct(
    private readonly EntityTypeManagerInterface $entityTypeManager,
  ) {}

  /**
   * {@inheritdoc}
   */
  public function getPublicKey(string $keyId): ?string {
    $publisher = $this->entityTypeManager
      ->getStorage('flowdrop_trusted_publisher')
      ->load($keyId);

    if ($publisher === NULL) {
      return NULL;
    }
    /** @var \Drupal\flowdrop\FlowDropTrustedPublisherInterface $publisher */
    if (!$publisher->isEnabled()) {
      return NULL;
    }

    $decoded = base64_decode($publisher->getPublicKey(), TRUE);
    if ($decoded === FALSE || strlen($decoded) !== SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES) {
      return NULL;
    }

    return $decoded;
  }

}
