<?php

declare(strict_types=1);

namespace Drupal\flowdrop_interrupt\Plugin\InterruptHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\flowdrop_interrupt\Attribute\FlowDropInterruptHandler;
use Drupal\flowdrop_interrupt\Entity\FlowDropInterruptInterface;

/**
 * Inbox handler for Pause signals.
 *
 * Pause signals are inward interrupts created by the `/pause` API endpoint.
 * The orchestrator pauses the pipeline and leaves the signal pending. The
 * signal then appears in the inbox; resolving it (via this handler's
 * single "Resume" button) triggers the standard
 * {@see \Drupal\flowdrop_interrupt\EventSubscriber\InterruptResolvedSubscriber}
 * which resumes the pipeline.
 *
 * The handler does not collect any user input — it's an acknowledgement
 * gesture only. The response data records the timestamp for audit.
 *
 * @internal
 */
#[FlowDropInterruptHandler(
  id: 'pause',
  label: new TranslatableMarkup('Pause signal'),
  description: 'Inbox display for paused pipelines',
)]
final class PauseInterruptHandler extends AbstractInterruptHandler implements HitlInterruptHandlerInterface {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function buildResolveForm(array $form, FormStateInterface $formState, FlowDropInterruptInterface $interrupt): array {
    $initiatorUid = $interrupt->getInitiatorUid();
    $reason = $interrupt->getReason();

    $form['pause_details'] = [
      '#type' => 'container',
      '#attributes' => ['class' => ['flowdrop-pause-details']],
    ];
    if ($reason !== NULL && $reason !== '') {
      $form['pause_details']['reason'] = [
        '#type' => 'item',
        '#title' => $this->t('Reason'),
        '#markup' => '<p>' . htmlspecialchars($reason, ENT_QUOTES, 'UTF-8') . '</p>',
      ];
    }
    if ($initiatorUid !== NULL) {
      $form['pause_details']['initiator'] = [
        '#type' => 'item',
        '#title' => $this->t('Paused by'),
        '#markup' => $this->t('User @uid', ['@uid' => $initiatorUid]),
      ];
    }

    $form['actions'] = ['#type' => 'actions'];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Resume'),
      '#button_type' => 'primary',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   *
   * No validation — clicking Resume is an unconditional acknowledgement.
   */
  public function validateForm(array &$form, FormStateInterface $formState, FlowDropInterruptInterface $interrupt): void {}

  /**
   * {@inheritdoc}
   */
  public function extractResponseFromForm(FormStateInterface $formState, FlowDropInterruptInterface $interrupt): mixed {
    return ['resumed_at' => time()];
  }

  /**
   * {@inheritdoc}
   */
  public function normalizeResponse(mixed $raw, FlowDropInterruptInterface $interrupt): mixed {
    if (is_array($raw)) {
      return $raw;
    }
    return ['resumed_at' => time()];
  }

}
