<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

/**
 * 界面文档 §2.1：`play.toggle` —— 玩法开关变更推送。
 *
 * 触发时机：后台开启或关闭某玩法时。
 * 前端处理：玩法列显示/隐藏或置灰/启用。
 */
final class PlayToggleBroadcast implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /** 异步广播队列 */
    public string $queue = 'broadcasts';

    /** 最多重试 3 次 */
    public int $tries = 3;

    /** 单任务超时 10 秒 */
    public int $timeout = 10;

    /**
     * @param  string  $playCode  玩法代码（如 straight_4d, box_2d 等）
     * @param  bool  $enabled  是否启用
     * @param  string|null  $reason  变更原因（可选）
     * @param  int  $emittedAtMs  发送时间戳（毫秒）
     */
    public function __construct(
        public readonly string $playCode,
        public readonly bool $enabled,
        public readonly ?string $reason,
        public readonly int $emittedAtMs,
    ) {}

    /**
     * 公共频道，所有在大厅的玩家都能收到。
     *
     * @return array<int, Channel>
     */
    public function broadcastOn(): array
    {
        return [new Channel('lottery-hall')];
    }

    public function broadcastAs(): string
    {
        return 'play.toggle';
    }

    /**
     * @return array{play_code: string, enabled: bool, reason: string|null, action: string, emitted_at_ms: int}
     */
    public function broadcastWith(): array
    {
        return [
            'play_code' => $this->playCode,
            'enabled' => $this->enabled,
            'reason' => $this->reason,
            'action' => $this->enabled ? 'enabled' : 'disabled',
            'emitted_at_ms' => $this->emittedAtMs,
        ];
    }
}
