<?php

declare(strict_types=1);

namespace Drupal\flowdrop_interrupt\Plugin\InterruptHandler;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\flowdrop_interrupt\Entity\FlowDropInterruptInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Convenience base class for interrupt handler plugins.
 *
 * Implements {@see InterruptHandlerInterface} with sensible defaults and
 * boilerplate for label/description/version from the plugin attribute.
 * Decorator-specific methods (HITL form building, scheduled sweeping,
 * webhook validation, queue delegation) remain abstract in their
 * respective interfaces — implement those where the capability applies.
 *
 * @api
 */
abstract class AbstractInterruptHandler extends PluginBase implements InterruptHandlerInterface, ContainerFactoryPluginInterface {

  /**
   * {@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 getId(): string {
    return (string) $this->getPluginId();
  }

  /**
   * {@inheritdoc}
   *
   * Returns the TranslatableMarkup from the plugin attribute when present,
   * falling back to a plain string. Callers are responsible for casting at
   * render time so the active language is honoured.
   */
  public function getLabel(): \Stringable|string {
    $definition = $this->getPluginDefinition();
    $label = is_array($definition) ? ($definition['label'] ?? '') : '';
    if ($label instanceof \Stringable) {
      return $label;
    }
    return (string) $label;
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription(): string {
    $definition = $this->getPluginDefinition();
    return is_array($definition) ? ((string) ($definition['description'] ?? '')) : '';
  }

  /**
   * {@inheritdoc}
   *
   * Default implementation passes through. HITL plugins typically override
   * to convert form values to the canonical shape.
   */
  public function normalizeResponse(mixed $raw, FlowDropInterruptInterface $interrupt): mixed {
    return $raw;
  }

}
