<?php

/**
 * 文件功能：赛马开赛广播事件
 *
 * 新场次开始押注时广播给房间所有用户，携带场次 ID、
 * 参赛马匹信息和押注截止时间，前端展示倒计时押注面板。
 *
 * @author  ChatRoom Laravel
 *
 * @version 1.0.0
 */

namespace App\Events;

use App\Models\HorseRace;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

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

    /**
     * @param  HorseRace  $race  本场信息
     */
    public function __construct(
        public readonly HorseRace $race,
    ) {}

    /**
     * 广播至房间公共频道。
     *
     * @return array<\Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        return [new PresenceChannel('room.1')];
    }

    /**
     * 广播事件名（前端监听 .horse.opened）。
     */
    public function broadcastAs(): string
    {
        return 'horse.opened';
    }

    /**
     * 广播数据。
     *
     * @return array<string, mixed>
     */
    public function broadcastWith(): array
    {
        return [
            'race_id' => $this->race->id,
            'horses' => $this->race->horses,
            'total_pool' => $this->race->total_pool,
            'bet_opens_at' => $this->race->bet_opens_at->toIso8601String(),
            'bet_closes_at' => $this->race->bet_closes_at->toIso8601String(),
            'bet_seconds' => (int) now()->diffInSeconds($this->race->bet_closes_at),
        ];
    }
}
