<?php

namespace App\MessageHandler;

use App\Message\MeilisearchMessage;
use App\Service\MeilisearchService;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
class MeilisearchMessageHandler
{
    public function __construct(
        private MeilisearchService $meilisearch,
    ) {
    }

    public function __invoke(MeilisearchMessage $message): void
    {
        match ($message->action) {
            'createIndex' => $this->meilisearch->request('POST', '/indexes', [
                'uid' => $message->index,
                'primaryKey' => $message->payload['primaryKey'] ?? 'id',
            ]),
            'deleteIndex' => $this->meilisearch->request('DELETE', "/indexes/{$message->index}"),
            'addDocuments' => $this->meilisearch->request('POST', "/indexes/{$message->index}/documents", $message->payload['documents']),
            'updateDocuments' => $this->meilisearch->request('PUT', "/indexes/{$message->index}/documents", $message->payload['documents']),
            'deleteDocument' => $this->meilisearch->request('DELETE', "/indexes/{$message->index}/documents/{$message->payload['documentId']}"),
            'deleteDocuments' => $this->meilisearch->request('POST', "/indexes/{$message->index}/documents/delete-batch", $message->payload['ids']),
            'updateSettings' => $this->meilisearch->request('PATCH', "/indexes/{$message->index}/settings", $message->payload['settings']),
            default => throw new \InvalidArgumentException("Unknown action: {$message->action}"),
        };

        $this->meilisearch->invalidateSearchCache();
    }
}
