<?php

// app/Events/WireChatUserTyping.php
namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

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

    public $conversationId;
    public $user;
    public $action; // 'start' or 'stop'
    public $timestamp;

    public function __construct($conversationId, $user, $action = 'start')
    {
        $this->conversationId = $conversationId;
        $this->user = $user;
        $this->action = $action;
        $this->timestamp = now();
    }

    public function broadcastOn()
    {
        // Broadcast to the conversation channel (similar to WireChat's MessageCreated event)
        return new PrivateChannel("conversation.{$this->conversationId}");
    }

    public function broadcastWith()
    {
        return [
            'conversation_id' => $this->conversationId,
            'user' => [
                'id' => $this->user->id,
                'name' => $this->user->name,
                'type' => $this->user->getMorphClass(),
                'avatar' => $this->user->avatar ?? null,
            ],
            'action' => $this->action,
            'timestamp' => $this->timestamp,
        ];
    }

    public function broadcastAs()
    {
        return 'WireChatUserTyping';
    }
}
