<?php

namespace Detektivo\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Helper\Table;

class ListIndexes extends Command {

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

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

    protected function configure(): void {
        $this
            ->setDescription('List all Detektivo search indexes')
            ->setHelp('This command lists all configured search indexes')
            ->addOption('types', 't', InputOption::VALUE_NONE, 'Also list available index types');
    }

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

        $detektivo = $this->app->module('detektivo');
        $showTypes = $input->getOption('types');

        $output->writeln('');

        // List available index types
        if ($showTypes) {
            $types = $detektivo->indexTypes();

            $output->writeln('<info>Available Index Types</info>');
            $output->writeln(str_repeat('-', 40));

            if (count($types)) {
                $table = new Table($output);
                $table->setHeaders(['Type', 'Label', 'Info']);

                foreach ($types as $name => $type) {
                    $table->addRow([
                        $name,
                        $type['label'] ?? $name,
                        $type['info'] ?? '-'
                    ]);
                }
                $table->render();
            } else {
                $output->writeln('<comment>No index types registered</comment>');
            }

            $output->writeln('');
        }

        // List configured indexes
        $indexes = $detektivo->indexes();

        $output->writeln('<info>Configured Indexes</info>');
        $output->writeln(str_repeat('-', 40));

        if (!count($indexes)) {
            $output->writeln('<comment>No indexes configured</comment>');
            $output->writeln('');
            return Command::SUCCESS;
        }

        $table = new Table($output);
        $table->setHeaders(['Name', 'Type', 'Label', 'Group', 'Created']);

        foreach ($indexes as $name => $index) {
            $table->addRow([
                $name,
                $index['type'] ?? 'unknown',
                $index['label'] ?? $name,
                $index['group'] ?? '-',
                isset($index['_created']) ? date('Y-m-d', $index['_created']) : '-'
            ]);
        }

        $table->render();
        $output->writeln('');

        return Command::SUCCESS;
    }
}
