<?php

declare(strict_types=1);

namespace Drupal\flowdrop_runtime\Form;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\flowdrop_runtime\Service\WorkflowState\EntitySnapshotStorage;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Form for cleaning up old workflow snapshots.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
final class SnapshotCleanupForm extends FormBase {

  /**
   * The entity snapshot storage service.
   *
   * @var \Drupal\flowdrop_runtime\Service\WorkflowState\EntitySnapshotStorage
   */
  protected EntitySnapshotStorage $snapshotStorage;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * Constructs a new SnapshotCleanupForm.
   *
   * @param \Drupal\flowdrop_runtime\Service\WorkflowState\EntitySnapshotStorage $snapshot_storage
   *   The entity snapshot storage service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(EntitySnapshotStorage $snapshot_storage, EntityTypeManagerInterface $entity_type_manager) {
    $this->snapshotStorage = $snapshot_storage;
    $this->entityTypeManager = $entity_type_manager;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'flowdrop_runtime_snapshot_cleanup';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $form['description'] = [
      '#type' => 'markup',
      '#markup' => '<p>' . $this->t('Use this form to clean up old workflow snapshots. This action is irreversible.') . '</p>',
    ];

    $form['age'] = [
      '#type' => 'select',
      '#title' => $this->t('Delete snapshots older than'),
      '#options' => [
        '3600' => $this->t('1 hour'),
        '86400' => $this->t('1 day'),
        '604800' => $this->t('1 week'),
        '2592000' => $this->t('30 days'),
        '7776000' => $this->t('90 days'),
      ],
      '#default_value' => '604800',
      '#required' => TRUE,
    ];

    $form['statuses'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Only delete snapshots with status'),
      '#options' => [
        'completed' => $this->t('Completed'),
        'failed' => $this->t('Failed'),
        'pending' => $this->t('Pending'),
        'running' => $this->t('Running'),
        'paused' => $this->t('Paused'),
      ],
      '#default_value' => ['completed', 'failed'],
      '#description' => $this->t('Leave all unchecked to delete all snapshots regardless of status.'),
    ];

    $form['actions'] = [
      '#type' => 'actions',
    ];

    $form['actions']['preview'] = [
      '#type' => 'submit',
      '#value' => $this->t('Preview'),
      '#submit' => ['::previewCleanup'],
    ];

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Delete snapshots'),
      '#button_type' => 'danger',
    ];

    return $form;
  }

  /**
   * Preview cleanup handler.
   */
  public function previewCleanup(array &$form, FormStateInterface $form_state): void {
    $age = (int) $form_state->getValue('age');
    $statuses = array_filter($form_state->getValue('statuses') ?? []);
    $olderThan = time() - $age;

    // Count snapshots that would be deleted.
    $query = $this->entityTypeManager
      ->getStorage('flowdrop_workflow_snapshot')
      ->getQuery()
      ->condition('created', $olderThan, '<')
      ->accessCheck(TRUE);

    if (!empty($statuses)) {
      $query->condition('snapshot_status', array_keys($statuses), 'IN');
    }

    $count = $query->count()->execute();

    $this->messenger()->addStatus($this->t('@count snapshots would be deleted.', [
      '@count' => $count,
    ]));
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $age = (int) $form_state->getValue('age');
    $statuses = array_filter($form_state->getValue('statuses') ?? []);
    $olderThan = time() - $age;

    $statusList = !empty($statuses) ? array_keys($statuses) : [];
    $deleted = $this->snapshotStorage->cleanup($olderThan, $statusList);

    $this->messenger()->addStatus($this->t('Deleted @count workflow snapshots.', [
      '@count' => $deleted,
    ]));

    $form_state->setRedirect('entity.flowdrop_workflow_snapshot.collection');
  }

}
