<?php

declare(strict_types=1);

namespace App\Framework\Telemetry;

/**
 * Handle for an active operation, providing a fluent API
 */
final class OperationHandle
{
    /**
     * @param string $operationId ID of the operation
     * @param TelemetryService $telemetryService Telemetry service that created this handle
     */
    public function __construct(
        private readonly string $operationId,
        private readonly TelemetryService $telemetryService
    ) {
    }

    /**
     * Get the operation ID
     */
    public function getId(): string
    {
        return $this->operationId;
    }

    /**
     * Add an attribute to the operation
     */
    public function addAttribute(string $key, mixed $value): self
    {
        $this->telemetryService->addOperationAttribute($this->operationId, $key, $value);

        return $this;
    }

    /**
     * End the operation with the given status and error message
     */
    public function end(string $status = 'success', ?string $errorMessage = null): self
    {
        $this->telemetryService->endOperation($this->operationId, $status, $errorMessage);

        return $this;
    }

    /**
     * Mark the operation as failed with the given error message
     */
    public function fail(string $errorMessage): self
    {
        return $this->end('error', $errorMessage);
    }

    /**
     * Record a metric within the context of this operation
     */
    public function recordMetric(string $name, float $value, string $unit = '', array $attributes = []): self
    {
        $this->telemetryService->recordMetric($name, $value, $unit, $attributes);

        return $this;
    }

    /**
     * Record an event within the context of this operation
     */
    public function recordEvent(string $name, array $attributes = [], string $severity = 'info'): self
    {
        $this->telemetryService->recordEvent($name, $attributes, $severity);

        return $this;
    }
}
