<?php

namespace App\Events;

use App\Models\User;
use App\Services\Messaging\MessagingPayloadFactory;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

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

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

    public function __construct(
        public int $conversationId,
        public User $user,
    ) {
        $this->queue = (string) config('messaging.broadcast.queue', 'broadcasts');
        $this->dontBroadcastToCurrentUser();
    }

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

    public function broadcastAs(): string
    {
        return 'typing.started';
    }

    public function broadcastWith(): array
    {
        return [
            'event' => 'typing.started',
            'conversation_id' => $this->conversationId,
            'user' => app(MessagingPayloadFactory::class)->userSummary($this->user),
            'expires_in_ms' => (int) config('messaging.typing.ttl_seconds', 8) * 1000,
        ];
    }
}
