<?php

declare(strict_types=1);

namespace App\Framework\Queue\MachineLearning\Events;

use App\Framework\Queue\MachineLearning\ValueObjects\JobAnomalyResult;
use App\Framework\Queue\ValueObjects\JobMetadata;
use App\Framework\Queue\ValueObjects\JobMetrics;

/**
 * Queue Job Anomaly Detected Event
 *
 * Dispatched when the anomaly monitor detects unusual job behavior.
 *
 * This event can be used to:
 * - Send notifications to monitoring systems
 * - Trigger automated remediation workflows
 * - Update dashboards and metrics
 * - Store anomaly results for analysis
 */
final readonly class QueueJobAnomalyDetectedEvent
{
    public function __construct(
        public JobMetrics $metrics,
        public JobMetadata $metadata,
        public JobAnomalyResult $anomalyResult
    ) {}

    /**
     * Get event type identifier
     */
    public function getEventType(): string
    {
        return 'queue.job.anomaly_detected';
    }

    /**
     * Get severity level
     */
    public function getSeverity(): string
    {
        return $this->anomalyResult->getSeverity();
    }

    /**
     * Check if this is a critical anomaly
     */
    public function isCritical(): bool
    {
        return $this->anomalyResult->requiresImmediateAttention();
    }

    /**
     * Get event payload for logging/notification
     */
    public function toArray(): array
    {
        return [
            'event_type' => $this->getEventType(),
            'job_id' => $this->metrics->jobId,
            'queue_name' => $this->metrics->queueName,
            'job_class' => $this->metadata->class->toString(),
            'anomaly_score' => $this->anomalyResult->anomalyScore->value(),
            'severity' => $this->getSeverity(),
            'is_critical' => $this->isCritical(),
            'primary_indicator' => $this->anomalyResult->primaryIndicator,
            'detected_patterns' => array_map(
                fn($pattern) => [
                    'type' => $pattern['type'],
                    'confidence' => $pattern['confidence']->value(),
                    'description' => $pattern['description']
                ],
                $this->anomalyResult->detectedPatterns
            ),
            'recommended_action' => $this->anomalyResult->getRecommendedAction(),
            'job_metrics' => [
                'execution_time_ms' => $this->metrics->executionTimeMs,
                'memory_usage_mb' => $this->metrics->getMemoryUsageMB(),
                'attempts' => $this->metrics->attempts,
                'status' => $this->metrics->status
            ],
            'timestamp' => date('Y-m-d H:i:s')
        ];
    }
}
