<?php

declare(strict_types=1);

namespace App\Command;

use App\Service\Prices\RedisImportService;
use Psr\Log\LoggerInterface;
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;
use Symfony\Component\Stopwatch\Stopwatch;
use Throwable;

#[AsCommand(
    name: 'mto:prices:import',
    description: 'Importiert verschachtelte ORM-Datenstruktur in Redis.'
)]
final class RedisImportCommand extends Command
{
    public function __construct(
        private readonly RedisImportService $importService,
        private readonly LoggerInterface $logger,
        private readonly Stopwatch $stopwatch
    ) {
        parent::__construct();
    }

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

        try {
            $this->stopwatch->start('price_import');

            $this->importService->writePrices($output);

            $event = $this->stopwatch->stop('price_import');
            $duration = number_format(($event?->getDuration() ?? 0) / 1000, 2);

            $io->success([
                'Preisdaten erfolgreich nach Redis importiert.',
                "Dauer: {$duration}s"
            ]);

            return Command::SUCCESS;

        } catch (Throwable $e) {
            $this->logger->error('Redis-Import fehlgeschlagen', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            $io->error('Fehler beim Redis-Import: ' . $e->getMessage());
            return Command::FAILURE;
        }
    }
}
