<?php

declare(strict_types=1);

namespace Drupal\node_revision_delete_protection\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Drupal\node\NodeInterface;
use Drupal\node_revision_delete_protection\RevisionProtectionManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Controller for revision protection operations.
 */
class RevisionManagerController extends ControllerBase {

  /**
   * Constructs a RevisionController object.
   *
   * @param \Drupal\node_revision_delete_protection\RevisionProtectionManager $revisionProtectionManager
   *   The revision manager service.
   */
  public function __construct(
    protected RevisionProtectionManager $revisionProtectionManager,
  ) {
  }

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

  /**
   * Protects a revision from cleanup.
   *
   * @param \Drupal\node\NodeInterface $node
   *   The node.
   * @param int $node_revision
   *   The revision ID.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Redirect response.
   */
  public function protect(NodeInterface $node, int $node_revision): RedirectResponse {
    $this->revisionProtectionManager->protect('node', (int) $node->id(), $node_revision);

    $this->messenger()->addStatus($this->t('Revision @vid has been protected from deletion.', [
      '@vid' => $node_revision,
    ]));

    $url = Url::fromRoute('entity.node.version_history', [
      'node' => $node->id(),
    ])->toString();

    return new RedirectResponse($url);
  }

  /**
   * Release revision protection.
   *
   * @param \Drupal\node\NodeInterface $node
   *   The node.
   * @param int $node_revision
   *   The revision ID.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Redirect response.
   */
  public function release(NodeInterface $node, int $node_revision): RedirectResponse {
    $this->revisionProtectionManager->release('node', $node_revision);

    $this->messenger()->addStatus($this->t('Revision @vid has been unprotected.', [
      '@vid' => $node_revision,
    ]));

    $url = Url::fromRoute('entity.node.version_history', [
      'node' => $node->id(),
    ])->toString();

    return new RedirectResponse($url);
  }

}
