<?php

declare(strict_types=1);

namespace Drupal\native_observability_spans\Service;

/**
 * Defines storage operations for execution spans.
 *
 * A span represents a timed unit of work, such as a service call, HTTP
 * call, or database query, linked to a request trace.
 */
interface SpanStorageInterface {

  /**
   * Inserts a span record into storage.
   *
   * @param array $span
   *   Normalized span data ready to be persisted.
   *
   * @return int
   *   The primary key ID of the inserted span record.
   */
  public function insert(array $span): int;

  /**
   * Marks a span as ended by span_id.
   *
   * @param string $span_id
   *   Span identifier.
   * @param int $ended_at_ms
   *   End time in epoch milliseconds.
   * @param int $duration_ms
   *   Duration in milliseconds.
   * @param string|null $payload_json
   *   Optional updated JSON payload (string).
   */
  public function end(string $span_id, int $ended_at_ms, int $duration_ms, ?string $payload_json = NULL): void;

  /**
   * Backfills trace_id for all spans produced within a request.
   *
   * This is needed because spans can be recorded before the trace row exists.
   *
   * @param string $request_id
   *   Request correlation identifier.
   * @param int $trace_id
   *   Inserted trace primary key.
   */
  public function attachTraceId(string $request_id, int $trace_id): void;

  /**
   * Loads spans by trace_id (ordered by started_at_ms ASC).
   *
   * @param int $trace_id
   *   Trace primary key.
   *
   * @return array
   *   List of span rows.
   */
  public function loadByTraceId(int $trace_id): array;

  /**
   * Loads spans by request_id (ordered by started_at_ms ASC).
   *
   * @param string $request_id
   *   Request correlation identifier.
   *
   * @return array
   *   List of span rows.
   */
  public function loadByRequestId(string $request_id): array;

  /**
   * Deletes all spans for a given request id.
   *
   * @param string $request_id
   *   The request id.
   *
   * @return int
   *   The number of deleted rows.
   */
  public function deleteByRequestId(string $request_id): int;

  /**
   * Deletes all spans.
   *
   * @return int
   *   The number of deleted rows.
   */
  public function deleteAll(): int;

}
