<?php

declare(strict_types=1);

namespace Drupal\farm_import_csv\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\migrate\Plugin\MigrationPluginManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides menu links for CSV importers.
 */
class CsvImportMenuLink extends DeriverBase implements ContainerDeriverInterface {

  public function __construct(
    protected MigrationPluginManagerInterface $migrationPluginManager,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, $base_plugin_id) {
    // @todo Remove when DeriverBase provides a create() method with autowiring.
    // @see https://www.drupal.org/project/drupal/issues/3565338
    return new static(
      $container->get('plugin.manager.migration'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {
    $links = [];

    // Load CSV importers.
    $importers = $this->migrationPluginManager->getDefinitions();

    // Add a link for each CSV importer in the farm_import_csv group.
    foreach ($importers as $id => $importer) {
      if (!($importer['source']['plugin'] == 'csv_file' && $importer['migration_group'] == 'farm_import_csv')) {
        continue;
      }
      $route_id = 'farm.import.csv.' . $id;
      $links[$route_id] = [
        'title' => $importer['label'],
        'parent' => 'farm.import.csv',
        'route_name' => 'farm.import.csv.importer',
        'route_parameters' => [
          'migration_id' => $id,
        ],
      ] + $base_plugin_definition;
    }

    return $links;
  }

}
