<?php

namespace App\MessageHandler;

use App\Message\MeilisearchSyncMessage;
use App\Repository\CustomerRepository;
use App\Repository\PriceAutomaticRepository;
use App\Repository\RevendeurRepository;
use App\Service\MeilisearchService;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
class MeilisearchSyncMessageHandler
{
    public function __construct(
        private MeilisearchService $meilisearch,
        private CustomerRepository $customerRepository,
        private RevendeurRepository $revendeurRepository,
        private PriceAutomaticRepository $priceRepository,
    ) {
    }

    public function __invoke(MeilisearchSyncMessage $message): void
    {
        if ('remove' === $message->action) {
            match ($message->type) {
                MeilisearchSyncMessage::TYPE_CUSTOMER => $this->meilisearch->removeCustomer($message->entityId),
                MeilisearchSyncMessage::TYPE_REVENDEUR => $this->meilisearch->removeRevendeur($message->entityId),
                MeilisearchSyncMessage::TYPE_PRICE => $this->meilisearch->removePrice($message->entityId),
                default => null,
            };

            return;
        }

        match ($message->type) {
            MeilisearchSyncMessage::TYPE_CUSTOMER => $this->indexCustomer($message->entityId),
            MeilisearchSyncMessage::TYPE_REVENDEUR => $this->indexRevendeur($message->entityId),
            MeilisearchSyncMessage::TYPE_PRICE => $this->indexPrice($message->entityId),
            default => null,
        };
    }

    private function indexCustomer(int $id): void
    {
        $customer = $this->customerRepository->find($id);
        if (null !== $customer) {
            $this->meilisearch->indexCustomer($customer);
        }
    }

    private function indexRevendeur(int $id): void
    {
        $revendeur = $this->revendeurRepository->find($id);
        if (null !== $revendeur) {
            $this->meilisearch->indexRevendeur($revendeur);
        }
    }

    private function indexPrice(int $id): void
    {
        $price = $this->priceRepository->find($id);
        if (null !== $price) {
            $this->meilisearch->indexPrice($price);
        }
    }
}
