<?php

namespace App\Events\Chat;

use App\Models\ChatMessage;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

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

    public function __construct(public readonly ChatMessage $message) {}

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

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

    public function broadcastWith(): array
    {
        $msg = $this->message;

        return [
            'id'            => $msg->id,
            'chat_group_id' => $msg->chat_group_id,
            'type'          => $msg->type,
            'body'          => $msg->body,
            'image_path'    => $msg->image_path,
            'is_pinned'     => $msg->is_pinned,
            'created_at'    => $msg->created_at,
            'user'          => [
                'id'                  => $msg->user->id,
                'name'                => $msg->user->name,
                'profile_photo'  => $msg->user->profile_photo,
            ],
        ];
    }
}
