<?php

/**
 * 文件功能：五子棋对局结束广播事件
 *
 * 对局结束（胜负/平局/认输/超时）时广播两个频道：
 * 1. 私有对局频道：通知双方结算并关闭棋盘
 * 2. 房间公共频道：广播战报消息
 *
 * @author  ChatRoom Laravel
 *
 * @version 1.0.0
 */

namespace App\Events;

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

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

    /**
     * @param  GomokuGame  $game  当前对局
     * @param  string  $winnerName  胜者用户名（平局时为空字符串）
     * @param  string  $loserName  败者用户名（平局时为空字符串）
     * @param  string  $reason  结束原因：win | draw | resign | timeout
     */
    public function __construct(
        public readonly GomokuGame $game,
        public readonly string $winnerName,
        public readonly string $loserName,
        public readonly string $reason,
    ) {}

    /**
     * 同时广播至对局私有频道 + 房间公共频道。
     *
     * @return array<\Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        return [
            new PrivateChannel("gomoku.{$this->game->id}"),
            new PresenceChannel("room.{$this->game->room_id}"),
        ];
    }

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

    /**
     * 广播数据。
     *
     * @return array<string, mixed>
     */
    public function broadcastWith(): array
    {
        return [
            'game_id' => $this->game->id,
            'winner' => $this->game->winner,
            'winner_name' => $this->winnerName,
            'loser_name' => $this->loserName,
            'reason' => $this->reason,
            'reward_gold' => $this->game->reward_gold,
            'mode' => $this->game->mode,
        ];
    }
}
