<?php

declare(strict_types=1);

namespace App\Framework\Waf\BotProtection\ValueObjects;

use App\Framework\Core\ValueObjects\Percentage;

/**
 * Bot risk score with factors and confidence
 */
final readonly class BotRiskScore
{
    public function __construct(
        public Percentage $score,
        public array $factors,
        public int $detectionCount,
        public Percentage $confidence
    ) {
    }

    /**
     * Create zero risk score
     */
    public static function zero(): self
    {
        return new self(
            score: Percentage::from(0.0),
            factors: [],
            detectionCount: 0,
            confidence: Percentage::from(0.0)
        );
    }

    /**
     * Get risk score value
     */
    public function getValue(): float
    {
        return $this->score->getValue();
    }

    /**
     * Check if risk is critical
     */
    public function isCritical(): bool
    {
        return $this->getValue() >= 90.0;
    }

    /**
     * Check if risk is high
     */
    public function isHigh(): bool
    {
        return $this->getValue() >= 75.0;
    }

    /**
     * Check if risk is elevated
     */
    public function isElevated(): bool
    {
        return $this->getValue() >= 50.0;
    }

    /**
     * Get dominant risk factor
     */
    public function getDominantFactor(): ?string
    {
        if (empty($this->factors)) {
            return null;
        }

        return array_keys($this->factors, max($this->factors))[0];
    }

    /**
     * Get risk level
     */
    public function getRiskLevel(): string
    {
        return match (true) {
            $this->isCritical() => 'CRITICAL',
            $this->isHigh() => 'HIGH',
            $this->isElevated() => 'MEDIUM',
            $this->getValue() >= 25.0 => 'LOW',
            default => 'MINIMAL'
        };
    }

    /**
     * Convert to array
     */
    public function toArray(): array
    {
        return [
            'score' => $this->getValue(),
            'level' => $this->getRiskLevel(),
            'factors' => $this->factors,
            'detection_count' => $this->detectionCount,
            'confidence' => $this->confidence->getValue(),
            'dominant_factor' => $this->getDominantFactor(),
            'is_critical' => $this->isCritical(),
            'is_high' => $this->isHigh(),
            'is_elevated' => $this->isElevated(),
        ];
    }
}
