<?php

namespace App\Commands;

use App\Broadcasting\Entity\WebsocketEventData;
use App\Broadcasting\Events\WebsocketEvent;
use Illuminate\Console\Command;

final class TestWebsocketEvent extends Command
{
    protected $signature = 'websocket:test
                            {room}
                            {--event=test-event}
                            {--data=}';

    protected $description = 'Test websocket broadcasting by emitting an event';

    public function handle(): int
    {
        try {
            $room  = $this->argument('room');
            $event = $this->option('event');

            $data = $this->option('data')
                ? json_decode($this->option('data'), true, 512, JSON_THROW_ON_ERROR)
                : ['message' => 'Test message'];

            $eventData = WebsocketEventData::from(
                room:  $room,
                data:  $data,
                event: $event
            );

            event(new WebsocketEvent($eventData));

            $this->info('Event broadcasted successfully');

            $this->table(
                ['Component', 'Value'],
                [
                    ['Room', $room],
                    ['Event', $event],
                    ['Data', json_encode($data, JSON_PRETTY_PRINT)],
                ]
            );

            return self::SUCCESS;
        } catch (\JsonException $e) {
            $this->error('Invalid JSON data provided');
            return self::FAILURE;
        } catch (\Throwable $e) {
            $this->error("Error broadcasting event: {$e->getMessage()}");
            return self::FAILURE;
        }
    }
}
