<?php

declare(strict_types=1);

namespace Drupal\native_observability_cache_observer\Service;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\native_observability\Service\ObservabilityCleanupHandlerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

/**
 * Cleanup handler for retained cache observer records.
 */
final class CacheObserverCleanupHandler implements ObservabilityCleanupHandlerInterface {

  /**
   * Creates a new cache observer cleanup handler instance.
   */
  public function __construct(
    private readonly CacheObserverStorage $storage,
    #[Autowire(service: 'config.factory')]
    private readonly ConfigFactoryInterface $configFactory,
  ) {
  }

  /**
   * Gets the cleanup handler identifier.
   */
  public function id(): string {
    return 'cache_observer';
  }

  /**
   * Checks whether cache observer cleanup can run.
   */
  public function isAvailable(): bool {
    return $this->storage->tableExists();
  }

  /**
   * Deletes stale cache observer records.
   */
  public function cleanup(array $settings): int {
    $moduleConfig = $this->configFactory->get('native_observability_cache_observer.settings');
    $retentionHours = (int) ($settings['cache_observer_retention_hours'] ?? $moduleConfig->get('retention_hours') ?? 72);
    $batchLimit = (int) ($settings['cleanup_batch_limit'] ?? 5000);
    $threshold = time() - max(1, $retentionHours) * 3600;

    return $this->storage->deleteOlderThan($threshold, $batchLimit);
  }

  /**
   * Removes all cache observer records.
   *
   * @return int
   *   The number of deleted rows.
   */
  public function cleanupAll(): int {
    return $this->storage->deleteAll();
  }

}
