<?php

namespace App\Events;

use App\Models\Participant;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class ParticipantJoined implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(public Participant $participant)
    {
        $this->participant->load('quiz');
    }

    public function broadcastOn(): array
    {
        return [new Channel('quiz.'.$this->participant->quiz->uuid)];
    }

    public function broadcastAs(): string
    {
        return 'participant.joined';
    }

    public function broadcastWith(): array
    {
        return [
            'participant' => [
                'id' => $this->participant->id,
                'name' => $this->participant->name,
                'session_uuid' => $this->participant->session_uuid,
                'score' => $this->participant->score,
                'joined_at' => optional($this->participant->created_at)->toIso8601String(),
            ],
            'total_participants' => $this->participant->quiz->participants()->count(),
        ];
    }
}
