<?php

namespace Drupal\acquia_contenthub_subscriber\EventSubscriber\PreEntitySave;

use Drupal\acquia_contenthub\AcquiaContentHubEvents;
use Drupal\acquia_contenthub\Event\PreEntitySaveEvent;
use Drupal\acquia_contenthub_subscriber\Libs\UserSyndicationSettingsInterface;
use Drupal\Core\Entity\RevisionLogInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Replaces revision user with proxy user.
 *
 * @package Drupal\acquia_contenthub_subscriber\EventSubscriber\PreEntitySave
 */
class ReplaceAuthorForRevisionWithProxyUser implements EventSubscriberInterface {

  /**
   * The user syndication settings.
   *
   * @var \Drupal\acquia_contenthub_subscriber\Libs\UserSyndicationSettingsInterface
   */
  protected UserSyndicationSettingsInterface $userSettings;

  /**
   * Constructs this object.
   *
   * @param \Drupal\acquia_contenthub_subscriber\Libs\UserSyndicationSettingsInterface $user_settings
   *   The user syndication settings.
   */
  public function __construct(UserSyndicationSettingsInterface $user_settings) {
    $this->userSettings = $user_settings;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events[AcquiaContentHubEvents::PRE_ENTITY_SAVE] = ['onPreEntitySave', 100];
    return $events;
  }

  /**
   * Set User id for new revisions.
   *
   * @param \Drupal\acquia_contenthub\Event\PreEntitySaveEvent $event
   *   The pre entity save event.
   */
  public function onPreEntitySave(PreEntitySaveEvent $event) {
    /** @var \Drupal\Core\Entity\RevisionLogInterface $entity */
    $entity = $event->getEntity();
    if ($this->userSettings->isUserSyndicationDisabled()) {
      $proxy = $this->userSettings->getProxyUser();
      if (!empty($proxy) && ($entity instanceof RevisionLogInterface)) {
        $entity->setRevisionUserId($proxy->id());
      }
    }
  }

}
