<?php

declare(strict_types=1);

namespace Tests\Performance\LoadTests;

/**
 * Load test result value object
 */
final readonly class LoadTestResult
{
    public function __construct(
        public int $totalRequests,
        public float $totalTimeMs,
        public float $avgResponseTimeMs,
        public float $minResponseTimeMs,
        public float $maxResponseTimeMs,
        public float $medianResponseTimeMs,
        public float $p95ResponseTimeMs,
        public float $p99ResponseTimeMs,
        public float $requestsPerSecond,
        public int $successfulRequests,
        public float $errorRate,
        public array $errors = []
    ) {}

    /**
     * Format result as human-readable string
     */
    public function toString(): string
    {
        return sprintf(
            "Load Test Results:\n" .
            "  Total Requests:    %d\n" .
            "  Successful:        %d (%.1f%%)\n" .
            "  Error Rate:        %.2f%%\n" .
            "  Total Time:        %.2fs\n" .
            "  Response Time:     avg=%.2fms, min=%.2fms, max=%.2fms, median=%.2fms\n" .
            "  Percentiles:       P95=%.2fms, P99=%.2fms\n" .
            "  Throughput:        %.2f requests/sec",
            $this->totalRequests,
            $this->successfulRequests,
            ($this->successfulRequests / $this->totalRequests) * 100,
            $this->errorRate,
            $this->totalTimeMs / 1000,
            $this->avgResponseTimeMs,
            $this->minResponseTimeMs,
            $this->maxResponseTimeMs,
            $this->medianResponseTimeMs,
            $this->p95ResponseTimeMs,
            $this->p99ResponseTimeMs,
            $this->requestsPerSecond
        );
    }

    /**
     * Convert to array for JSON serialization
     */
    public function toArray(): array
    {
        return [
            'total_requests' => $this->totalRequests,
            'successful_requests' => $this->successfulRequests,
            'error_rate' => round($this->errorRate, 2),
            'time' => [
                'total_ms' => round($this->totalTimeMs, 2),
                'total_seconds' => round($this->totalTimeMs / 1000, 2),
            ],
            'response_time' => [
                'avg_ms' => round($this->avgResponseTimeMs, 2),
                'min_ms' => round($this->minResponseTimeMs, 2),
                'max_ms' => round($this->maxResponseTimeMs, 2),
                'median_ms' => round($this->medianResponseTimeMs, 2),
                'p95_ms' => round($this->p95ResponseTimeMs, 2),
                'p99_ms' => round($this->p99ResponseTimeMs, 2),
            ],
            'throughput' => [
                'requests_per_second' => round($this->requestsPerSecond, 2),
            ],
            'errors' => $this->errors
        ];
    }
}
