<?php

declare(strict_types=1);

namespace App\Framework\Http\Emitter;

use App\Framework\Http\Response;
use App\Framework\Http\Responses\WebSocketResponse;
use App\Framework\Http\WebSocketServer;

final class WebSocketEmitter implements Emitter
{
    public function __construct(
        private readonly WebSocketServer $webSocketServer = new WebSocketServer()
    ) {
    }

    public function emit(Response $response): void
    {
        if ($response instanceof WebSocketResponse === false) {
            throw new \InvalidArgumentException('Response must be an instance of WebSocketResponse');
        }

        // 1. Robustheit: Prüfen, ob Header bereits gesendet wurden.
        if (headers_sent($file, $line)) {
            throw new \RuntimeException("Kann die WebSocket-Antwort nicht senden: Header wurden bereits in {$file}:{$line} gesendet.");
        }

        // 2. Output-Buffer leeren
        if (ob_get_level() > 0 && ob_get_length() > 0) {
            ob_clean();
        }

        // 3. Status-Code senden
        http_response_code($response->status->value);

        // 4. Header senden
        foreach ($response->headers->toArray() as $name => $value) {
            $headerValue = is_array($value) ? implode(', ', $value) : $value;
            header("$name: $headerValue", true);
        }

        // 5. Output-Buffer leeren und alle Header senden
        flush();

        // 6. WebSocket-Server mit der Verbindung beginnen
        $this->webSocketServer->handleUpgrade($response);
    }
}
