<?php

namespace App\Events;

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

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

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

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

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

    public function broadcastAs(): string
    {
        return 'conversation.updated';
    }

    public function broadcastWith(): array
    {
        return [
            'event' => 'conversation.updated',
            'reason' => $this->reason,
            'conversation' => app(MessagingPayloadFactory::class)->conversationSummary($this->conversation, $this->userId),
            'summary' => [
                'unread_total' => app(UnreadCounterService::class)->totalUnreadForUser($this->userId),
            ],
        ];
    }
}
