<?php

declare(strict_types=1);

namespace Drupal\native_observability_database_observer\Service;

/**
 * Collects database runtime counters for the current execution flow.
 *
 * This collector is intentionally minimal. It stores only aggregated counters
 * in memory so the request can be persisted once at the end of the trace flow.
 * Slow queries are handled separately by the RAW storage layer.
 */
final class DatabaseQueryRuntimeCollector {

  /**
   * Total number of captured queries for the current execution flow.
   */
  private int $queryCount = 0;

  /**
   * Total measured database time in milliseconds.
   */
  private float $totalQueryTimeMs = 0.0;

  /**
   * Number of queries considered slow for the current execution flow.
   */
  private int $slowQueryCount = 0;

  /**
   * Current execution context type.
   *
   * Expected values:
   * - http
   * - cli
   * - unrelated.
   */
  private string $contextType = 'http';

  /**
   * Resets the in-memory counters for a new execution flow.
   */
  public function reset(string $contextType = 'http'): void {
    $this->queryCount = 0;
    $this->totalQueryTimeMs = 0.0;
    $this->slowQueryCount = 0;
    $this->contextType = $contextType;
  }

  /**
   * Records a single measured query.
   */
  public function recordQuery(float $durationMs, bool $isSlow): void {
    $this->queryCount++;
    $this->totalQueryTimeMs += $durationMs;

    if ($isSlow) {
      $this->slowQueryCount++;
    }
  }

  /**
   * Returns the current request-level summary.
   */
  public function getRequestSummary(): array {
    return [
      'context_type' => $this->contextType,
      'query_count' => $this->queryCount,
      'total_query_time_ms' => round($this->totalQueryTimeMs, 3),
      'slow_query_count' => $this->slowQueryCount,
    ];
  }

}
