<?php

namespace App\Service;

use App\Entity\BilletBuyer;
use Doctrine\ORM\EntityManagerInterface;

class OrderIndexService
{
    private const INDEX_PREFIX = 'order_event_';

    public function __construct(
        private readonly MeilisearchService $meilisearch,
        private readonly EntityManagerInterface $em,
    ) {
    }

    /**
     * @return list<BilletBuyer>
     */
    public function searchOrders(int $eventId, string $query): array
    {
        $index = self::INDEX_PREFIX.$eventId;

        if ('' === $query) {
            return [];
        }

        try {
            $results = $this->meilisearch->search($index, $query);
            $ids = array_map(fn (array $hit) => $hit['id'], $results['hits'] ?? []);

            return $ids ? $this->em->getRepository(BilletBuyer::class)->findBy(['id' => $ids]) : [];
        } catch (\Throwable) {
            return [];
        }
    }

    public function indexOrder(BilletBuyer $order): void
    {
        try {
            $index = self::INDEX_PREFIX.$order->getEvent()->getId();
            $this->meilisearch->createIndexIfNotExists($index);
            $this->meilisearch->addDocuments($index, [$this->toDocument($order)]);
        } catch (\Throwable) {
            // Meilisearch unavailable
        }
    }

    /**
     * @return array<string, mixed>
     */
    private function toDocument(BilletBuyer $order): array
    {
        $items = [];
        foreach ($order->getItems() as $item) {
            $items[] = $item->getBilletName().' x'.$item->getQuantity();
        }

        return [
            'id' => $order->getId(),
            'orderNumber' => $order->getOrderNumber(),
            'reference' => $order->getReference(),
            'firstName' => $order->getFirstName(),
            'lastName' => $order->getLastName(),
            'email' => $order->getEmail(),
            'status' => $order->getStatus(),
            'totalHT' => $order->getTotalHTDecimal(),
            'items' => implode(', ', $items),
            'createdAt' => $order->getCreatedAt()->format('Y-m-d H:i'),
        ];
    }
}
