<?php

declare(strict_types=1);

namespace App\Framework\Monitoring;

use App\Framework\Core\ValueObjects\Timestamp;

/**
 * Monitoring alert value object
 */
final readonly class MonitoringAlert
{
    public function __construct(
        public string $type, // 'circuit_breaker', 'error_boundary', 'system'
        public string $severity, // 'info', 'warning', 'critical'
        public string $component,
        public string $message,
        public Timestamp $timestamp,
        public array $metrics = [],
        public ?string $alertId = null,
    ) {
    }

    /**
     * Get alert priority (1-5, 5 being highest)
     */
    public function getPriority(): int
    {
        return match ($this->severity) {
            'info' => 1,
            'warning' => 3,
            'critical' => 5,
            default => 2,
        };
    }

    /**
     * Check if alert requires immediate attention
     */
    public function requiresImmediateAttention(): bool
    {
        return $this->severity === 'critical';
    }

    /**
     * Get alert age
     */
    public function getAge(Timestamp $currentTime): \App\Framework\Core\ValueObjects\Duration
    {
        return $this->timestamp->diff($currentTime);
    }

    /**
     * Convert to array for serialization
     */
    public function toArray(): array
    {
        return [
            'alert_id' => $this->alertId ?? uniqid('alert_', true),
            'type' => $this->type,
            'severity' => $this->severity,
            'priority' => $this->getPriority(),
            'component' => $this->component,
            'message' => $this->message,
            'timestamp' => $this->timestamp->toIsoString(),
            'requires_immediate_attention' => $this->requiresImmediateAttention(),
            'metrics' => $this->metrics,
        ];
    }

    /**
     * Create from array
     */
    public static function fromArray(array $data): self
    {
        return new self(
            type: $data['type'],
            severity: $data['severity'],
            component: $data['component'],
            message: $data['message'],
            timestamp: Timestamp::fromFloat(strtotime($data['timestamp'])),
            metrics: $data['metrics'] ?? [],
            alertId: $data['alert_id'] ?? null,
        );
    }
}
