<?php

namespace Drupal\acquia_contenthub_subscriber\Libs;

use Drupal\user\RoleInterface;
use Drupal\user\UserInterface;
use Psr\Log\LoggerInterface;

/**
 * Responsible for handling user and user role deletions.
 */
class UserDeletionHandler implements UserDeletionHandlerInterface {

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

  /**
   * The acquia_contenthub_subscriber logger channel.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected LoggerInterface $logger;

  /**
   * Constructs a new object.
   *
   * @param \Drupal\acquia_contenthub_subscriber\Libs\UserSyndicationSettingsInterface $settings
   *   The user syndication settings.
   * @param \Psr\Log\LoggerInterface $logger
   *   The acquia_contenthub_subscriber logger channel.
   */
  public function __construct(UserSyndicationSettingsInterface $settings, LoggerInterface $logger) {
    $this->userSettings = $settings;
    $this->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public function blockUser(UserInterface $user): void {
    if ($this->userSettings->isUserSyndicationDisabled()) {
      $this->logger->debug('Blocking of user ({uuid}) interrupted. Reason: User syndication is disabled.', [
        'uuid' => $user->uuid(),
      ]);
      return;
    }

    user_cancel([], $user->id(), 'user_cancel_block');
    // Since user_cancel() is not invoked via Form API, batch processing
    // needs to be invoked manually.
    $batch =& batch_get();
    // Mark this batch as non-progressive to bypass the progress bar and
    // redirect.
    $batch['progressive'] = FALSE;
    batch_process();
  }

  /**
   * {@inheritdoc}
   */
  public function deleteUserRole(RoleInterface $role): void {
    if ($this->userSettings->isUserRoleSyndicationDisabled()) {
      $this->logger->debug('Deletion of user role ({uuid}) interrupted. Reason: User role syndication is disabled.', [
        'uuid' => $role->uuid(),
      ]);
      return;
    }
    try {
      $role->delete();
    }
    catch (\Exception $e) {
      $this->logger->error('Error during user role ({id}) deletion: {error}', [
        'error' => $e->getMessage(),
        'id' => $role->id(),
      ]);
    }
  }

}
