<?php

declare(strict_types=1);

namespace Drupal\flowdrop_workflow_executor\Plugin\Deriver;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\flowdrop_workflow\WorkflowDefinitionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Generates one WorkflowNode derivative per FlowDropWorkflow entity.
 *
 * Each derivative appears on the canvas as the target workflow itself, with
 * typed input / output ports derived from the workflow's declared schema.
 *
 * Plugin IDs follow the Drupal derivative convention:
 * `flowdrop_workflow:<workflow_id>`.
 *
 * @internal
 */
final class WorkflowNodeDeriver extends DeriverBase implements ContainerDeriverInterface {

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

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, $base_plugin_id): static {
    return new static(
      $container->get('entity_type.manager'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition): array {
    $storage = $this->entityTypeManager->getStorage('flowdrop_workflow');
    foreach ($storage->loadMultiple() as $workflow) {
      if (!$workflow instanceof WorkflowDefinitionInterface) {
        continue;
      }
      $id = (string) $workflow->id();
      $this->derivatives[$id] = [
        'label' => new TranslatableMarkup('Run workflow: @label', ['@label' => (string) $workflow->label()]),
        'description' => $workflow->getDescription(),
        'workflow_id' => $id,
      ] + $base_plugin_definition;
    }
    return $this->derivatives;
  }

}
