<?php

declare(strict_types=1);

namespace Drupal\flowdrop\Entity;

use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\Core\Entity\Attribute\ConfigEntityType;
use Drupal\Core\Entity\EntityDeleteForm;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\flowdrop\Form\FlowDropTrustedPublisherForm;
use Drupal\flowdrop\FlowDropTrustedPublisherInterface;
use Drupal\flowdrop\FlowDropTrustedPublisherListBuilder;

/**
 * Defines the trusted workflow-bundle publisher entity type.
 *
 * The entity id is the publisher key id, matched against a bundle signature's
 * key_id during verification.
 *
 * @internal
 *   This class is not part of the public API and may change without notice.
 */
#[ConfigEntityType(
  id: 'flowdrop_trusted_publisher',
  label: new TranslatableMarkup('Trusted Publisher'),
  label_collection: new TranslatableMarkup('Trusted Publishers'),
  label_singular: new TranslatableMarkup('trusted publisher'),
  label_plural: new TranslatableMarkup('trusted publishers'),
  config_prefix: 'flowdrop_trusted_publisher',
  entity_keys: [
    'id' => 'id',
    'label' => 'label',
    'uuid' => 'uuid',
    'status' => 'enabled',
  ],
  handlers: [
    'list_builder' => FlowDropTrustedPublisherListBuilder::class,
    'route_provider' => [
      'html' => AdminHtmlRouteProvider::class,
    ],
    'form' => [
      'add' => FlowDropTrustedPublisherForm::class,
      'edit' => FlowDropTrustedPublisherForm::class,
      'delete' => EntityDeleteForm::class,
    ],
  ],
  links: [
    'collection' => '/admin/flowdrop/config/trusted-publishers',
    'add-form' => '/admin/flowdrop/config/trusted-publishers/add',
    'edit-form' => '/admin/flowdrop/config/trusted-publishers/{flowdrop_trusted_publisher}',
    'delete-form' => '/admin/flowdrop/config/trusted-publishers/{flowdrop_trusted_publisher}/delete',
  ],
  admin_permission: 'administer flowdrop trusted publishers',
  label_count: [
    'singular' => '@count trusted publisher',
    'plural' => '@count trusted publishers',
  ],
  config_export: [
    'id',
    'label',
    'uuid',
    'public_key',
    'enabled',
  ],
)]
final class FlowDropTrustedPublisher extends ConfigEntityBase implements FlowDropTrustedPublisherInterface {

  /**
   * The publisher key id (also the signature key_id it is matched against).
   */
  protected string $id;

  /**
   * The human-readable publisher label.
   */
  protected string $label;

  /**
   * The base64-encoded Ed25519 public key.
   */
  protected string $public_key = '';

  /**
   * Whether this publisher is enabled (grants trust).
   */
  protected bool $enabled = TRUE;

  /**
   * {@inheritdoc}
   */
  public function getPublicKey(): string {
    return $this->public_key;
  }

  /**
   * {@inheritdoc}
   */
  public function isEnabled(): bool {
    return $this->enabled;
  }

}
