<?php

use App\Models\Conversation;
use App\Policies\ConversationPolicy;
use App\Services\Messaging\MessagingPayloadFactory;
use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Broadcast::channel('user.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Broadcast::channel('private-user.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Broadcast::channel('conversation.{conversationId}', function ($user, $conversationId) {
    $conversation = Conversation::query()->find($conversationId);

    if (! $conversation) {
        return false;
    }

    return app(ConversationPolicy::class)->view($user, $conversation);
});

Broadcast::channel('private-conversation.{conversationId}', function ($user, $conversationId) {
    $conversation = Conversation::query()->find($conversationId);

    if (! $conversation) {
        return false;
    }

    return app(ConversationPolicy::class)->view($user, $conversation);
});

Broadcast::channel('presence-conversation.{conversationId}', function ($user, $conversationId) {
    $conversation = Conversation::query()->find($conversationId);

    if (! $conversation || ! app(ConversationPolicy::class)->joinPresence($user, $conversation)) {
        return false;
    }

    return app(MessagingPayloadFactory::class)->presenceUser($user);
});

Broadcast::channel('presence-messaging', function ($user) {
    return app(MessagingPayloadFactory::class)->presenceUser($user);
});
