<?php

namespace App\Services\Messaging;

use App\Jobs\DeleteMessageFromIndexJob;
use App\Jobs\IndexMessageJob;
use App\Models\Message;

class MessageSearchIndexer
{
    public function indexMessage(Message $message): void
    {
        IndexMessageJob::dispatch($message->id);
    }

    public function updateMessage(Message $message): void
    {
        IndexMessageJob::dispatch($message->id);
    }

    public function deleteMessage(Message $message): void
    {
        DeleteMessageFromIndexJob::dispatch($message->id);
    }

    public function rebuildConversation(int $conversationId): void
    {
        Message::query()
            ->where('conversation_id', $conversationId)
            ->whereNull('deleted_at')
            ->select('id')
            ->chunkById(200, function ($messages): void {
                foreach ($messages as $message) {
                    IndexMessageJob::dispatch((int) $message->id);
                }
            });
    }

    public function rebuildAll(): void
    {
        Message::query()
            ->whereNull('deleted_at')
            ->select('id')
            ->chunkById(500, function ($messages): void {
                foreach ($messages as $message) {
                    IndexMessageJob::dispatch((int) $message->id);
                }
            });
    }
}
