<?php

use Illuminate\Support\Facades\Broadcast;

// 用户私有频道：仅允许用户本人订阅自己的通知频道。
Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

// 聊天室房间 Presence Channel 鉴权与成员信息抓取
Broadcast::channel('room.{roomId}', function ($user, $roomId) {
    $room = \App\Models\Room::find($roomId);
    if (! $room || ! $room->canUserEnter($user)) {
        return false;
    }

    $chatState = app(\App\Services\ChatStateService::class);
    if (! $chatState->isUserInRoom((int) $roomId, $user->username)) {
        return false;
    }

    return app(\App\Services\ChatUserPresenceService::class)->build($user);
});

// 用户私有频道鉴权（好友通知：FriendAdded / FriendRemoved / BannerNotification）
// 使用数字 ID 命名频道，避免中文用户名导致 Pusher 频道名验证失败。
Broadcast::channel('user.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

// 五子棋对局私有频道（仅对局双方可订阅，用于实时同步落子）
Broadcast::channel('gomoku.{gameId}', function ($user, $gameId) {
    $game = \App\Models\GomokuGame::find($gameId);
    if (! $game) {
        return false;
    }

    return $game->belongsToUser($user->id);
});
