<?php

namespace App\Events;

use App\Models\Conversation;
use App\Models\Message;
use App\Services\Messaging\MessagingPayloadFactory;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class MessageCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public bool $afterCommit = true;
    public string $queue;

    public function __construct(
        public Conversation $conversation,
        public Message $message,
        int $originUserId,
    ) {
        $this->queue = (string) config('messaging.broadcast.queue', 'broadcasts');

        if ($originUserId === (int) $message->sender_id) {
            $this->dontBroadcastToCurrentUser();
        }
    }

    public function broadcastOn(): array
    {
        return [new PrivateChannel('conversation.' . $this->conversation->id)];
    }

    public function broadcastAs(): string
    {
        return 'message.created';
    }

    public function broadcastWith(): array
    {
        return [
            'event' => 'message.created',
            'conversation_id' => (int) $this->conversation->id,
            'message' => app(MessagingPayloadFactory::class)->message($this->message, (int) $this->message->sender_id),
        ];
    }
}
