<?php

declare(strict_types=1);

namespace Drupal\native_observability_database_observer\Service;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\native_observability\Service\ObservabilityCleanupHandlerInterface;

/**
 * Removes expired database observer RAW records.
 */
final class DatabaseObserverCleanupHandler implements ObservabilityCleanupHandlerInterface {

  /**
   * Creates a new cleanup handler instance.
   */
  public function __construct(
    private readonly DatabaseObserverStorage $storage,
    private readonly ConfigFactoryInterface $configFactory,
  ) {
  }

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

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

  /**
   * Deletes rows older than the configured retention window.
   */
  public function cleanup(array $settings): int {
    $hours = (int) ($this->configFactory
      ->get('native_observability_database_observer.settings')
      ->get('retention_hours') ?? 72);

    return $this->storage->deleteOlderThan(
      time() - max(1, $hours) * 3600
    );
  }

  /**
   * Removes all stored database observer records.
   */
  public function cleanupAll(): int {
    return $this->storage->deleteAll();
  }

}
