<?php

declare(strict_types=1);

namespace App\Framework\Database\Cache\ValueObjects;

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

/**
 * Memory usage metrics value object
 */
final readonly class MemoryUsageMetrics
{
    public function __construct(
        public Byte $current,
        public Byte $peak,
        public Byte $limit,
        public Percentage $usagePercentage
    ) {
    }

    public function isNearLimit(): bool
    {
        return $this->usagePercentage->isAbove(Percentage::from(80.0));
    }

    public function isCritical(): bool
    {
        return $this->usagePercentage->isCritical(90.0);
    }

    public function getAvailable(): Byte
    {
        return $this->limit->isEmpty()
            ? Byte::zero()
            : $this->limit->subtract($this->current);
    }

    public function toArray(): array
    {
        return [
            'current' => $this->current->toHumanReadable(),
            'current_bytes' => $this->current->toBytes(),
            'peak' => $this->peak->toHumanReadable(),
            'peak_bytes' => $this->peak->toBytes(),
            'limit' => $this->limit->isEmpty() ? 'unlimited' : $this->limit->toHumanReadable(),
            'limit_bytes' => $this->limit->toBytes(),
            'usage_percentage' => $this->usagePercentage->format(),
            'available' => $this->getAvailable()->toHumanReadable(),
            'is_near_limit' => $this->isNearLimit(),
            'is_critical' => $this->isCritical(),
        ];
    }
}
