<?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\WebSocketResult;

/**
 * Response-Klasse für WebSocket-Upgrade
 */
final readonly class WebSocketResponse implements Response, Streamable
{
    public Status $status;
    public Headers $headers;
    public string $body;

    public function __construct(
        private WebSocketResult $webSocketResult,
        private string          $websocketKey
    ) {
        $this->status = $webSocketResult->status;

        // WebSocket-Upgrade-Header
        $headerData = [
            'Upgrade' => 'websocket',
            'Connection' => 'Upgrade',
            'Sec-WebSocket-Accept' => $this->generateAcceptKey($this->websocketKey),
        ];

        // Subprotokoll hinzufügen, falls unterstützt
        $subprotocols = $webSocketResult->getSubprotocols();
        if (!empty($subprotocols)) {
            $headerData['Sec-WebSocket-Protocol'] = implode(', ', $subprotocols);
        }

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

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

    /**
     * Generiert den Accept-Key für WebSocket-Handshake
     */
    private function generateAcceptKey(string $key): string
    {
        return base64_encode(hash('sha1', $key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
    }

    public function getWebSocketResult(): WebSocketResult
    {
        return $this->webSocketResult;
    }
}
