<?php

namespace App\Command;

use App\Repository\CustomerRepository;
use App\Repository\RevendeurRepository;
use App\Service\MeilisearchService;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'app:meilisearch:setup',
    description: 'Initialise les index Meilisearch et reindexe toutes les donnees',
)]
class MeilisearchSetupCommand extends Command
{
    public function __construct(
        private MeilisearchService $meilisearch,
        private CustomerRepository $customerRepository,
        private RevendeurRepository $revendeurRepository,
    ) {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        $io->section('Configuration des index');
        $this->meilisearch->setupIndexes();
        $io->info('Index customer et reseller configures.');

        $io->section('Indexation des clients');
        $customers = $this->customerRepository->findAll();
        foreach ($customers as $customer) {
            $this->meilisearch->indexCustomer($customer);
        }
        $io->info(sprintf('%d client(s) indexe(s).', \count($customers)));

        $io->section('Indexation des revendeurs');
        $revendeurs = $this->revendeurRepository->findAll();
        foreach ($revendeurs as $revendeur) {
            $this->meilisearch->indexRevendeur($revendeur);
        }
        $io->info(sprintf('%d revendeur(s) indexe(s).', \count($revendeurs)));

        $io->success('Meilisearch configure et donnees indexees.');

        return Command::SUCCESS;
    }
}
