<?php

declare(strict_types=1);

namespace Drupal\flowdrop_node_processor\Plugin\FlowDropNodeProcessor;

use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\flowdrop\Attribute\FlowDropNodeProcessor;
use Drupal\flowdrop\DTO\ParameterBagInterface;
use Drupal\flowdrop\DTO\ValidationResult;
use Drupal\flowdrop\Plugin\FlowDropNodeProcessor\AbstractFlowDropNodeProcessor;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Repeats a value N times for use with ForEach loops.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
#[FlowDropNodeProcessor(
  id: "repeat",
  label: new TranslatableMarkup("Repeat"),
  description: "Repeat a value N times",
  version: "1.0.0"
)]
class Repeat extends AbstractFlowDropNodeProcessor {

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
    return new static($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public function validateParams(array $params): ValidationResult {
    $count = $params['count'] ?? NULL;
    if ($count === NULL) {
      return ValidationResult::error('count', 'Count is required', 'MISSING_COUNT');
    }
    if ($count < 0) {
      return ValidationResult::error('count', 'Count must be non-negative', 'INVALID_COUNT');
    }
    return ValidationResult::success();
  }

  /**
   * {@inheritdoc}
   */
  public function process(ParameterBagInterface $params): array {
    $value = $params->get('value', NULL);
    $count = $params->getInt('count', 0);

    $items = $count > 0 ? array_fill(0, $count, $value) : [];

    return [
      'items' => $items,
      'count' => count($items),
      'value' => $value,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getParameterSchema(): array {
    return [
      'type' => 'object',
      'properties' => [
        'value' => [
          'type' => 'mixed',
          'title' => 'Value',
          'description' => 'The value to repeat',
        ],
        'count' => [
          'type' => 'integer',
          'title' => 'Count',
          'description' => 'Number of times to repeat the value',
          'minimum' => 0,
        ],
      ],
      'required' => ['count'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getOutputSchema(): array {
    return [
      'type' => 'object',
      'properties' => [
        'items' => [
          'type' => 'array',
          'description' => 'Array of repeated values',
        ],
        'count' => [
          'type' => 'integer',
          'description' => 'Number of items in the array',
        ],
        'value' => [
          'type' => 'mixed',
          'description' => 'The value that was repeated',
        ],
      ],
    ];
  }

}
