<?php

declare(strict_types=1);

namespace App\Framework\Waf\BotProtection\ValueObjects;

use App\Framework\Core\ValueObjects\Percentage;
use App\Framework\Core\ValueObjects\Timestamp;
use App\Framework\Waf\BotProtection\BotDetectionType;
use App\Framework\Waf\DetectionSeverity;

/**
 * Individual bot detection result
 */
final readonly class BotDetection
{
    public function __construct(
        public BotDetectionType $type,
        public DetectionSeverity $severity,
        public string $message,
        public array $evidence,
        public Percentage $confidence,
        public string $source,
        public ?Timestamp $timestamp = null
    ) {
        $this->timestamp = $timestamp ?? Timestamp::fromFloat(microtime(true));
    }

    /**
     * Check if this detection should block the request
     */
    public function shouldBlock(): bool
    {
        return $this->type->shouldBlock() ||
               ($this->severity === DetectionSeverity::HIGH && $this->confidence->getValue() >= 90.0);
    }

    /**
     * Check if this detection should trigger an alert
     */
    public function shouldAlert(): bool
    {
        return $this->severity->shouldAlert() || $this->confidence->getValue() >= 80.0;
    }

    /**
     * Check if this detection is high confidence
     */
    public function isHighConfidence(): bool
    {
        return $this->confidence->getValue() >= 80.0;
    }

    /**
     * Get risk contribution score
     */
    public function getRiskContribution(): float
    {
        $severityMultiplier = match($this->severity) {
            DetectionSeverity::CRITICAL => 1.0,
            DetectionSeverity::HIGH => 0.8,
            DetectionSeverity::MEDIUM => 0.6,
            DetectionSeverity::LOW => 0.4,
            DetectionSeverity::INFO => 0.2
        };

        return ($this->confidence->getValue() / 100) * $severityMultiplier * 100;
    }

    /**
     * Convert to array
     */
    public function toArray(): array
    {
        return [
            'type' => $this->type->value,
            'type_description' => $this->type->getDescription(),
            'severity' => $this->severity->value,
            'message' => $this->message,
            'evidence' => $this->evidence,
            'confidence' => $this->confidence->getValue(),
            'source' => $this->source,
            'timestamp' => $this->timestamp->toIsoString(),
            'should_block' => $this->shouldBlock(),
            'should_alert' => $this->shouldAlert(),
            'is_high_confidence' => $this->isHighConfidence(),
            'risk_contribution' => $this->getRiskContribution(),
        ];
    }
}
