<?php

/**
 * 文件功能：用户发送新消息广播事件
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Events;

use App\Models\User;
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 MessageSent implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @param  int  $roomId  房间ID
     * @param  array  $message  发送的消息数据
     */
    public function __construct(
        public readonly int $roomId,
        public readonly array $message,
    ) {}

    /**
     * 获取消息应广播到的频道。
     *
     * 公共消息走房间 Presence 频道；
     * 定向消息 / 悄悄话只发给发送方与接收方的私有用户频道。
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        if ($this->shouldBroadcastPrivately()) {
            $privateChannels = [];

            foreach ($this->resolveVisibleUserIds() as $userId) {
                $privateChannels[] = new PrivateChannel('user.'.$userId);
            }

            return $privateChannels;
        }

        return [
            new PresenceChannel('room.'.$this->roomId),
        ];
    }

    /**
     * 获取广播时的数据
     *
     * @return array<string, mixed>
     */
    public function broadcastWith(): array
    {
        return [
            'message' => $this->message,
        ];
    }

    /**
     * 判断当前消息是否应仅广播给特定用户。
     */
    private function shouldBroadcastPrivately(): bool
    {
        $toUser = trim((string) ($this->message['to_user'] ?? ''));

        return $toUser !== '' && $toUser !== '大家';
    }

    /**
     * 解析本条消息真正可见的用户 ID 列表。
     *
     * @return array<int, int>
     */
    private function resolveVisibleUserIds(): array
    {
        $userIds = [];

        $fromUser = trim((string) ($this->message['from_user'] ?? ''));
        if ($fromUser !== '') {
            $senderId = User::query()->where('username', $fromUser)->value('id');
            if ($senderId !== null) {
                $userIds[] = (int) $senderId;
            }
        }

        $toUser = trim((string) ($this->message['to_user'] ?? ''));
        if ($toUser !== '' && $toUser !== '大家') {
            $receiverId = User::query()->where('username', $toUser)->value('id');
            if ($receiverId !== null) {
                $userIds[] = (int) $receiverId;
            }
        }

        return array_values(array_unique($userIds));
    }
}
