<?php

declare(strict_types=1);

namespace MonsieurBiz\SyliusSearchPlugin\Command;

use MonsieurBiz\SyliusSearchPlugin\Exception\ReadOnlyIndexException;
use MonsieurBiz\SyliusSearchPlugin\Model\Document\Index\IndexerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\LockableTrait;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(
    name: 'monsieurbiz:search:populate',
    description: 'Populate the search index',
)]
class PopulateCommand extends Command
{
    use LockableTrait;

    public function __construct(private readonly IndexerInterface $documentIndexer)
    {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        if (!$this->lock()) {
            $output->writeln('The command is already running in another process.');

            return Command::FAILURE;
        }

        $output->writeln('Generating index');

        try {
            $this->documentIndexer->indexAll();
        } catch (ReadOnlyIndexException $exception) {
            $output->writeln('Cannot purge old index. Please to do it manually if needed.');
            $output->writeln($exception->getMessage());
            $this->release();

            return Command::FAILURE;
        }

        $output->writeln('Generated index');
        $this->release();

        return Command::SUCCESS;
    }
}
