<?php

namespace App\Services\Messenger;

use App\Models\Messenger\UserEvent;
use Illuminate\Support\Facades\DB;

class EventDispatcher
{
    /**
     * Dispatch an event to specific users
     */
    public function dispatch(string $type, array $data, array $userIds = []): void
    {
        if (empty($userIds)) {
            return;
        }

        $events = [];
        foreach ($userIds as $userId) {
            $events[] = [
                'user_id' => $userId,
                'type' => $type,
                'data' => json_encode($data),
                'created_at' => now(),
                'updated_at' => now(),
            ];
        }

        if (!empty($events)) {
            UserEvent::insert($events);
        }
    }

    /**
     * Dispatch conversation events
     */
    public function dispatchConversationEvent(string $type, array $data, int $conversationId): void
    {
        // Get all participants in the conversation
        $participantIds = DB::table('conversation_participants')
            ->where('conversation_id', $conversationId)
            ->whereNull('left_at')
            ->pluck('user_id')
            ->toArray();

        $this->dispatch($type, $data, $participantIds);
    }

    /**
     * Dispatch message events
     */
    public function dispatchMessageEvent(string $type, array $data, int $conversationId): void
    {
        $this->dispatchConversationEvent($type, $data, $conversationId);
    }

    /**
     * Dispatch typing events
     */
    public function dispatchTypingEvent(string $type, array $data, int $conversationId): void
    {
        $this->dispatchConversationEvent($type, $data, $conversationId);
    }
}
