<?php

declare(strict_types=1);

namespace App\Framework\Process\ValueObjects\Network;

use App\Framework\Core\ValueObjects\Duration;

/**
 * Ping Test Result.
 */
final readonly class PingResult
{
    public function __construct(
        public string $host,
        public bool $isReachable,
        public ?Duration $latency = null,
        public ?int $packetsSent = null,
        public ?int $packetsReceived = null,
        public ?float $packetLoss = null
    ) {
    }

    /**
     * Erstellt ein erfolgreiches Ping-Ergebnis.
     */
    public static function success(
        string $host,
        Duration $latency,
        int $packetsSent = 4,
        int $packetsReceived = 4
    ): self {
        $packetLoss = $packetsSent > 0
            ? (($packetsSent - $packetsReceived) / $packetsSent) * 100
            : 0.0;

        return new self(
            host: $host,
            isReachable: true,
            latency: $latency,
            packetsSent: $packetsSent,
            packetsReceived: $packetsReceived,
            packetLoss: $packetLoss
        );
    }

    /**
     * Erstellt ein fehlgeschlagenes Ping-Ergebnis.
     */
    public static function failed(string $host): self
    {
        return new self(
            host: $host,
            isReachable: false
        );
    }

    /**
     * Konvertiert zu Array.
     *
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'host' => $this->host,
            'is_reachable' => $this->isReachable,
            'latency_ms' => $this->latency?->toMilliseconds(),
            'latency_human' => $this->latency?->toHumanReadable(),
            'packets_sent' => $this->packetsSent,
            'packets_received' => $this->packetsReceived,
            'packet_loss_percent' => $this->packetLoss,
        ];
    }
}
