<?php

declare(strict_types=1);

namespace App\Framework\ErrorReporting\Analytics\ValueObjects;

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

/**
 * Represents error velocity (rate of change over time)
 */
final readonly class ErrorVelocity
{
    public function __construct(
        public DateTimeImmutable $period,
        public int $count,
        public int $previousCount,
        public int $change,
        public Percentage $velocityPercentage,
        public VelocityDirection $direction
    ) {
    }

    public static function calculate(
        DateTimeImmutable $period,
        int $currentCount,
        int $previousCount
    ): self {
        $change = $currentCount - $previousCount;
        $velocityPercent = $previousCount > 0 ? ($change / $previousCount) * 100 : 0;

        return new self(
            period: $period,
            count: $currentCount,
            previousCount: $previousCount,
            change: $change,
            velocityPercentage: Percentage::from(abs($velocityPercent)),
            direction: $change > 0 ? VelocityDirection::INCREASING :
                      ($change < 0 ? VelocityDirection::DECREASING : VelocityDirection::STABLE)
        );
    }

    public function isIncreasing(): bool
    {
        return $this->direction === VelocityDirection::INCREASING;
    }

    public function isDecreasing(): bool
    {
        return $this->direction === VelocityDirection::DECREASING;
    }

    public function isStable(): bool
    {
        return $this->direction === VelocityDirection::STABLE;
    }

    public function isSignificantChange(): bool
    {
        return $this->velocityPercentage->getValue() > 10.0;
    }

    public function isCriticalChange(): bool
    {
        return $this->velocityPercentage->getValue() > 50.0;
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'period' => $this->period->format('Y-m-d H:i:s'),
            'count' => $this->count,
            'previous_count' => $this->previousCount,
            'change' => $this->change,
            'velocity_percentage' => $this->velocityPercentage->getValue(),
            'direction' => $this->direction->value,
        ];
    }
}
