<?php

declare(strict_types=1);

namespace App\Framework\Redis\ValueObjects;

use App\Framework\Core\ValueObjects\Duration;
use DateTimeImmutable;

final readonly class RedisSlowLogEntry
{
    public function __construct(
        public int $id,
        public DateTimeImmutable $timestamp,
        public Duration $duration,
        public string $command,
        public array $fullCommand
    ) {
    }

    public static function create(int $id, int $timestamp, int $durationMicros, array $command): self
    {
        return new self(
            id: $id,
            timestamp: (new DateTimeImmutable())->setTimestamp($timestamp),
            duration: Duration::fromMicroseconds($durationMicros),
            command: self::formatCommand($command),
            fullCommand: $command
        );
    }

    private static function formatCommand(array $command): string
    {
        // Limit command display to first 3 parts for readability
        $displayParts = array_slice($command, 0, 3);
        $hasMore = count($command) > 3;

        return implode(' ', $displayParts) . ($hasMore ? '...' : '');
    }

    public function isSlow(?Duration $threshold = null): bool
    {
        $threshold ??= Duration::fromMilliseconds(100); // Default 100ms

        return $this->duration->isGreaterThan($threshold);
    }

    public function getCommandType(): string
    {
        return strtoupper($this->fullCommand[0] ?? 'UNKNOWN');
    }

    public function getSeverityLevel(): string
    {
        $ms = $this->duration->toMilliseconds();

        return match (true) {
            $ms >= 1000 => 'Critical',
            $ms >= 500 => 'High',
            $ms >= 100 => 'Medium',
            default => 'Low'
        };
    }

    public function getSeverityIcon(): string
    {
        return match ($this->getSeverityLevel()) {
            'Critical' => '🔴',
            'High' => '🟠',
            'Medium' => '🟡',
            'Low' => '🟢',
            default => '⚪'
        };
    }
}
