<?php

declare(strict_types=1);

namespace Drupal\flowdrop_pipeline\Hook;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Hook\Attribute\Hook;
use Drupal\flowdrop_pipeline\Entity\FlowDropPipelineInterface;
use Drupal\user\UserInterface;

/**
 * User-related hook implementations for the flowdrop_pipeline module.
 *
 * Handles cleanup of FlowDrop Pipeline entities when user accounts are
 * cancelled or deleted.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
final class UserHooks {

  /**
   * Constructs a new UserHooks object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   */
  public function __construct(
    protected readonly EntityTypeManagerInterface $entityTypeManager,
  ) {}

  /**
   * Implements hook_user_cancel().
   */
  #[Hook('user_cancel')]
  public function userCancel($edit, UserInterface $account, $method): void {
    $storage = $this->entityTypeManager->getStorage('flowdrop_pipeline');

    switch ($method) {
      case 'user_cancel_block_unpublish':
        // Unpublish flowdrop pipelines.
        $flowdrop_pipeline_ids = $storage->getQuery()
          ->condition('uid', $account->id())
          ->condition('status', 1)
          // Access bypassed: system hook runs without user context.
          ->accessCheck(FALSE)
          ->execute();
        foreach ($storage->loadMultiple($flowdrop_pipeline_ids) as $flowdrop_pipeline) {
          if ($flowdrop_pipeline instanceof FlowDropPipelineInterface) {
            $flowdrop_pipeline->set('status', FALSE)->save();
          }
        }
        break;

      case 'user_cancel_reassign':
        // Anonymize flowdrop pipelines.
        $flowdrop_pipeline_ids = $storage->getQuery()
          ->condition('uid', $account->id())
          // Access bypassed: system hook runs without user context.
          ->accessCheck(FALSE)
          ->execute();
        foreach ($storage->loadMultiple($flowdrop_pipeline_ids) as $flowdrop_pipeline) {
          if ($flowdrop_pipeline instanceof FlowDropPipelineInterface) {
            $flowdrop_pipeline->setOwnerId(0)->save();
          }
        }
        break;
    }
  }

  /**
   * Implements hook_ENTITY_TYPE_predelete() for user entities.
   */
  #[Hook('user_predelete')]
  public function userPredelete(UserInterface $account): void {
    $storage = $this->entityTypeManager->getStorage('flowdrop_pipeline');
    $flowdrop_pipeline_ids = $storage->getQuery()
      ->condition('uid', $account->id())
      // Access bypassed: system hook runs without user context.
      ->accessCheck(FALSE)
      ->execute();
    $storage->delete(
      $storage->loadMultiple($flowdrop_pipeline_ids)
    );
  }

}
