<?php

namespace App\Events;

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

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

    public function __construct(public Quiz $quiz, public QuizQuestion $question)
    {
        $this->question->load('options');
    }

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

    public function broadcastAs(): string
    {
        return 'question.started';
    }

    public function broadcastWith(): array
    {
        return [
            'quiz' => [
                'uuid' => $this->quiz->uuid,
                'status' => $this->quiz->status,
            ],
            'question' => [
                'id' => $this->question->id,
                'sort_order' => $this->question->sort_order,
                'text' => $this->question->question_text,
                'duration_seconds' => $this->question->duration_seconds,
                'started_at' => optional($this->quiz->current_question_started_at)->toIso8601String(),
                'ends_at' => optional($this->quiz->current_question_ends_at)->toIso8601String(),
                'options' => $this->question->options->map(fn ($option) => [
                    'id' => $option->id,
                    'text' => $option->option_text,
                    'sort_order' => $option->sort_order,
                ])->values(),
            ],
        ];
    }
}
