<?php

declare(strict_types=1);

namespace Blax\WebRtc\Console\Commands;

use Blax\ReactPhpKernel\Kernel;
use Blax\WebRtc\Contracts\CallEventListener;
use Blax\WebRtc\Contracts\RoomAuthorizer;
use Blax\WebRtc\Recording\FileRecordingStore;
use Blax\WebRtc\Signaling\RelaySignalingHandler;
use Blax\Ws\WebSocketServer;
use Illuminate\Console\Command;

class StartWebRtcServer extends Command
{
    protected $signature = 'webrtc:serve {--host= : Bind host (defaults to config webrtc.host)} {--port= : Bind port (defaults to config webrtc.port)}';

    protected $description = 'Start the blax WebRTC signaling relay (WebSocket) on the shared ReactPHP kernel — typed rooms, presence and optional call recording.';

    public function handle(): int
    {
        $host = (string) ($this->option('host') ?: config('webrtc.host', '127.0.0.1'));
        $port = (int) ($this->option('port') ?: config('webrtc.port', 8090));

        $recorder = config('webrtc.recording.enabled')
            ? new FileRecordingStore(
                (string) config('webrtc.recording.path', 'webrtc'),
                (string) config('webrtc.recording.format', 'webm'),
            )
            : null;

        $handler = new RelaySignalingHandler(
            authorizer: app(RoomAuthorizer::class),
            recorder: $recorder,
            events: app(CallEventListener::class),
        );

        $kernel = (new Kernel)->reapChildren();
        $kernel->register(new WebSocketServer($host, $port, $handler, (array) config('webrtc.tls', [])));

        $recording = $recorder !== null ? 'on' : 'off';
        $this->info("blax WebRTC relay on ws://{$host}:{$port} — typed rooms + presence, recording {$recording}. Ctrl-C to stop.");

        $kernel->run();

        return self::SUCCESS;
    }
}
