<?php

declare(strict_types=1);

namespace App\Framework\DDoS\Analysis\ValueObjects;

use App\Framework\Core\ValueObjects\CountryCode;
use App\Framework\Core\ValueObjects\Score;

/**
 * Represents country-specific risk assessment for DDoS detection
 */
final readonly class CountryRisk
{
    public function __construct(
        public CountryCode $countryCode,
        public CountryRiskLevel $riskLevel,
        public Score $riskScore,
        public bool $isHighRisk,
        public bool $isBotFarmCountry,
        public bool $isAnonymous
    ) {
    }

    public static function analyze(CountryCode $countryCode): self
    {
        $isAnonymous = $countryCode->isAnonymous();
        $isHighRisk = $countryCode->isHighRiskCountry();
        $isBotFarm = $countryCode->isBotFarmCountry();

        // Calculate risk score
        $score = 0.0;
        if ($isAnonymous) {
            $score += 0.9;
        } elseif ($isHighRisk) {
            $score += 0.7;
        } elseif ($isBotFarm) {
            $score += 0.5;
        } else {
            $score = 0.1;
        }

        $riskLevel = match (true) {
            $score >= 0.8 => CountryRiskLevel::CRITICAL,
            $score >= 0.6 => CountryRiskLevel::HIGH,
            $score >= 0.3 => CountryRiskLevel::MEDIUM,
            default => CountryRiskLevel::LOW
        };

        return new self(
            countryCode: $countryCode,
            riskLevel: $riskLevel,
            riskScore: Score::fromFloat($score),
            isHighRisk: $isHighRisk,
            isBotFarmCountry: $isBotFarm,
            isAnonymous: $isAnonymous
        );
    }

    public function isCritical(): bool
    {
        return $this->riskLevel === CountryRiskLevel::CRITICAL;
    }

    public function requiresBlocking(): bool
    {
        return $this->riskScore->value() >= 0.8;
    }

    public function requiresThrottling(): bool
    {
        return $this->riskScore->value() >= 0.5;
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'country_code' => $this->countryCode->toString(),
            'risk_level' => $this->riskLevel->value,
            'risk_score' => $this->riskScore->value(),
            'is_high_risk' => $this->isHighRisk,
            'is_bot_farm_country' => $this->isBotFarmCountry,
            'is_anonymous' => $this->isAnonymous,
        ];
    }
}
