<?php

namespace App\Events;

use App\Models\Conversation;
use App\Models\Message;
use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

class NewInboxMessage implements ShouldBroadcastNow
{
    public function __construct(
        public readonly Message      $message,
        public readonly Conversation $conversation,
    ) {}

    public function broadcastOn(): Channel
    {
        // Public channel per user — inbox-{user_id}
        return new Channel('inbox-' . $this->conversation->user_id);
    }

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

    public function broadcastWith(): array
    {
        return [
            'conversation_id'   => $this->conversation->id,
            'contact_phone'     => $this->conversation->contact_phone,
            'contact_name'      => $this->conversation->contact_name,
            'unread_count'      => $this->conversation->unread_count,
            'last_message'      => $this->conversation->last_message,
            'last_message_at'   => $this->conversation->last_message_at?->toISOString(),
            'message' => [
                'id'             => $this->message->id,
                'direction'      => $this->message->direction,
                'type'           => $this->message->type,
                'content'        => $this->message->content,
                'media_url'      => $this->message->media_url,
                'media_filename' => $this->message->media_filename,
                'created_at'     => $this->message->created_at?->toISOString(),
            ],
        ];
    }
}
