<?php

declare(strict_types=1);

namespace Drupal\node_revision_delete_protection\Plugin\NodeRevisionDelete;

use Drupal\Core\Database\Connection;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node_revision_delete_protection\RevisionProtectionManager;
use Drupal\node_revision_delete\Plugin\NodeRevisionDeleteBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Prevents deletion of protected revisions.
 *
 * @NodeRevisionDelete(
 *   id = "protected_revision",
 *   label = @Translation("Protected Revision"),
 *   description = @Translation("Prevents deletion of revisions that have been manually protected."),
 *   weight = -100
 * )
 */
class ProtectedRevision extends NodeRevisionDeleteBase {

  /**
   * The revision manager service.
   *
   * @var \Drupal\node_revision_delete_protection\RevisionProtectionManager
   */
  protected RevisionProtectionManager $revisionProtectionManager;

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected Connection $connection;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->revisionProtectionManager = $container->get('node_revision_delete_protection.manager');
    $instance->connection = $container->get('database');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function checkRevisions(array $revision_ids, int $active_vid): array {
    $revision_statuses = [];

    $protections = $this->connection->select('revision_protection', 'rp')
      ->fields('rp', ['revision_id', 'revision_id'])
      ->condition('entity_type', 'node')
      ->condition('revision_id', $revision_ids, 'IN')
      ->execute()
      ->fetchCol();

    foreach ($revision_ids as $vid) {
      $revision_statuses[$vid] = in_array($vid, $protections, FALSE) ? FALSE : TRUE;
    }

    return $revision_statuses;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state): array {
    $form['info'] = [
      '#type' => 'markup',
      '#prefix' => '<p>',
      '#markup' => $this->t('This plugin prevents deletion of revisions that have been manually protected.'),
      '#suffix' => '</p>',
    ];

    return $form;
  }

}
