<?php

namespace Detektivo\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;

class Clear extends Command {

    protected static $defaultName = 'detektivo:clear';
    protected ?\Lime\App $app = null;

    public function __construct(\Lime\App $app) {
        $this->app = $app;
        parent::__construct();
    }

    protected function configure(): void {
        $this
            ->setDescription('Clear documents from a Detektivo search index')
            ->setHelp('This command clears all documents from a search index without removing the index configuration')
            ->addArgument('name', InputArgument::REQUIRED, 'Name of the index to clear')
            ->addOption('force', 'f', InputOption::VALUE_NONE, 'Skip confirmation prompt');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int {

        $detektivo = $this->app->module('detektivo');
        $indexName = $input->getArgument('name');
        $force = $input->getOption('force');

        if (!$detektivo->exists($indexName)) {
            $output->writeln("<error>[x] Index '{$indexName}' not found</error>");
            return Command::FAILURE;
        }

        // Confirm unless --force is used
        if (!$force) {
            $helper = $this->getHelper('question');
            $question = new ConfirmationQuestion(
                "Are you sure you want to clear all documents from index '{$indexName}'? [y/N] ",
                false
            );

            if (!$helper->ask($input, $output, $question)) {
                $output->writeln('<comment>Operation cancelled</comment>');
                return Command::SUCCESS;
            }
        }

        $output->writeln('');
        $output->writeln("<comment>Clearing index:</comment> {$indexName}");

        try {
            $idx = $detektivo->index($indexName);

            if (!$idx) {
                $output->writeln('<error>[x] Could not access index</error>');
                return Command::FAILURE;
            }

            $idx->clear();
            $output->writeln('<info>[✓] Index cleared successfully</info>');
            $output->writeln('');

        } catch (\Throwable $e) {
            $output->writeln("<error>[x] Error: {$e->getMessage()}</error>");
            return Command::FAILURE;
        }

        return Command::SUCCESS;
    }
}
