<?php

declare(strict_types=1);

namespace App\Framework\ErrorBoundaries\Events;

use App\Framework\Core\ValueObjects\Duration;
use App\Framework\Core\ValueObjects\Timestamp;
use App\Framework\ErrorBoundaries\CircuitBreaker\BoundaryCircuitState;

/**
 * Event fired when circuit breaker recovers (closes)
 */
final readonly class BoundaryCircuitBreakerRecovered implements BoundaryEventInterface
{
    public readonly string $eventType;

    public readonly Timestamp $occurredAt;

    public readonly string $severity;

    public function __construct(
        public string $boundaryName,
        public BoundaryCircuitState $previousState,
        public BoundaryCircuitState $newState,
        public Duration $downTime,
        public int $successCount,
        public ?string $message = null,
        public array $context = [],
    ) {
        $this->eventType = 'boundary.circuit_breaker.recovered';
        $this->occurredAt = Timestamp::now();
        $this->severity = 'info';
    }

    public function getEventId(): string
    {
        return "boundary_circuit_recovery_{$this->boundaryName}_{$this->occurredAt->toFloat()}";
    }

    public function shouldAlert(): bool
    {
        return false; // Recovery is good news, typically no alert needed
    }

    public function toArray(): array
    {
        return [
            'event_id' => $this->getEventId(),
            'event_type' => $this->eventType,
            'boundary_name' => $this->boundaryName,
            'previous_state' => $this->previousState->value,
            'new_state' => $this->newState->value,
            'down_time_ms' => $this->downTime->toMilliseconds(),
            'down_time_human' => $this->downTime->toHumanReadable(),
            'success_count' => $this->successCount,
            'state_description' => $this->newState->getDescription(),
            'message' => $this->message,
            'context' => $this->context,
            'occurred_at' => $this->occurredAt->toIsoString(),
            'severity' => $this->severity,
            'should_alert' => $this->shouldAlert(),
        ];
    }
}
