<?php

namespace App\Events;

use App\Models\Conversation;
use App\Models\ConversationParticipant;
use App\Models\User;
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 MessageRead implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

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

    public function __construct(
        public Conversation $conversation,
        public ConversationParticipant $participant,
        public User $reader,
    ) {
        $this->queue = (string) config('messaging.broadcast.queue', 'broadcasts');
        $this->dontBroadcastToCurrentUser();
    }

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

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

    public function broadcastWith(): array
    {
        return [
            'event' => 'message.read',
            'conversation_id' => (int) $this->conversation->id,
            'user' => app(MessagingPayloadFactory::class)->userSummary($this->reader),
            'last_read_message_id' => $this->participant->last_read_message_id ? (int) $this->participant->last_read_message_id : null,
            'last_read_at' => optional($this->participant->last_read_at)?->toIso8601String(),
        ];
    }
}
