<?php

declare(strict_types=1);

namespace Drupal\flowdrop_memory\Hook;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Hook\Attribute\Hook;
use Psr\Log\LoggerInterface;

/**
 * Cron hook implementations for the flowdrop_memory module.
 *
 * Deletes expired memory record entities that are no longer accessed.
 * Without this, expired records are only cleaned up on read (lazy deletion),
 * leaving orphaned rows for records that are never read again.
 *
 * @internal
 */
final class CronHooks {

  /**
   * Maximum number of expired records to delete per cron run.
   */
  private const BATCH_SIZE = 500;

  /**
   * Constructs a new CronHooks object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   * @param \Psr\Log\LoggerInterface $logger
   *   The logger channel.
   */
  public function __construct(
    private readonly EntityTypeManagerInterface $entityTypeManager,
    private readonly LoggerInterface $logger,
  ) {}

  /**
   * Implements hook_cron().
   *
   * Deletes expired memory record entities in batches.
   */
  #[Hook('cron')]
  public function cron(): void {
    $storage = $this->entityTypeManager->getStorage('flowdrop_memory_record');

    $ids = $storage
      ->getQuery()
      ->accessCheck(FALSE)
      ->condition('expires', time(), '<')
      ->condition('expires', NULL, 'IS NOT NULL')
      ->range(0, self::BATCH_SIZE)
      ->execute();

    if (empty($ids)) {
      return;
    }

    $records = $storage->loadMultiple($ids);
    $storage->delete($records);

    $this->logger->info('Cron: deleted @count expired memory records.', [
      '@count' => count($records),
    ]);
  }

}
