<?php

declare(strict_types=1);

namespace App\Framework\Http\Responses;

use App\Framework\Http\Headers;
use App\Framework\Http\Response;
use App\Framework\Http\Status;
use App\Framework\Router\Result\SseEvent;
use App\Framework\Router\Result\SseResult;
use Closure;

/**
 * Response-Klasse für Server-Sent Events
 */
final class SseResponse implements Response, Streamable
{
    public readonly Status $status;

    public readonly Headers $headers;

    public readonly string $body;

    public array $initialEvents = [];

    /**
     * @var int Maximale Streaming-Dauer in Sekunden (0 = unbegrenzt)
     */
    public readonly int $maxDuration;

    /**
     * @var int Intervall für Heartbeats in Sekunden
     */
    public readonly int $heartbeatInterval;

    /**
     * @param SseResult $sseResult Das SseResult, aus dem die Response erstellt wird
     * @param Closure|null $streamCallback
     */
    public function __construct(SseResult $sseResult, public readonly ?Closure $streamCallback = null)
    {
        $this->status = $sseResult->status;

        $this->body = '';

        // Standard SSE-Header
        $headerData = [
            'Content-Type' => 'text/event-stream',
            'Cache-Control' => 'no-cache',
            'Connection' => 'keep-alive',
            'X-Accel-Buffering' => 'no', // Nginx buffering deaktivieren
        ];

        // Benutzerdefinierte Header hinzufügen
        foreach ($sseResult->headers as $name => $value) {
            $headerData[$name] = $value;
        }

        $this->headers = new Headers($headerData);

        // Initiale Events aus dem SseResult speichern
        $this->initialEvents = $sseResult->getInitialEvents();

        // Globales Retry-Interval setzen, falls definiert
        if ($sseResult->retryInterval !== null) {
            $this->initialEvents[] = new SseEvent('', null, null, $sseResult->retryInterval);
        }

        $this->maxDuration = $sseResult->maxDuration;
        $this->heartbeatInterval = $sseResult->heartbeatInterval;
        ;
    }
}
