<?php

namespace App\Command;

use App\Helper\HiltesImport;
use App\Helper\Jtl;
use App\Repository\ProductRepository;
use App\Repository\StockRepository;
use App\Repository\WarehouseRepository;
use Psr\Log\LoggerInterface;
use Sentry\CheckIn;
use Sentry\CheckInStatus;
use Symfony\Component\Console\Attribute\AsCommand;
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\Style\SymfonyStyle;
use Symfony\Component\HttpKernel\KernelInterface;
use function Sentry\captureCheckIn;

#[AsCommand(
    name: 'hiltes:import',
    description: 'Importiert die Bestandsdaten von Hiltes',
)]
class HiltesImportCommand extends Command
{
    private $stockRepository;
    private $warehouseRepository;
    private $productRepository;
    private $logger;

    public function __construct(
        ProductRepository   $productRepository,
        StockRepository     $stockRepository,
        WarehouseRepository $warehouseRepository,
        LoggerInterface     $logger
    )
    {
        $this->productRepository = $productRepository;
        $this->stockRepository = $stockRepository;
        $this->warehouseRepository = $warehouseRepository;
        $this->logger = $logger;
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->addOption('delta', 'd', InputOption::VALUE_NONE, 'Delta Import');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $time_start = microtime(true);

        // 🟡 Notify Sentry your job is running:
        $checkInId = captureCheckIn(
            slug: 'bestandsabgleich-delta',
            status: CheckInStatus::inProgress()
        );

        $io = new SymfonyStyle($input, $output);

        $io->success('Start Hiltes Import');
        $rootPath = $this->GetProjectRootDir();

        $delta = $input->getOption('delta');
        /**
         * @var HiltesImport
         */
        $hiltesImport = new HiltesImport($this->productRepository, $this->warehouseRepository, $this->stockRepository, $this->logger, $rootPath);

        $prodIds = $hiltesImport->startImport($delta);

        if (isset($r['error'])) {
            $io->error($r['text']);
            $this->logger->error($r['text']);

            // 🔴 Notify Sentry your job has failed:
            captureCheckIn(
                slug: 'bestandsabgleich-delta',
                status: CheckInStatus::error(),
                checkInId: $checkInId,
            );

            return Command::FAILURE;
        } else {
            $io->info('Start Hiltes Push JTL');

            $jtl = new Jtl($this->productRepository, $this->warehouseRepository, $this->stockRepository, $this->logger, $rootPath);

            //Export für Standartlager
            $jtl->createExportFile($jtl->getProducts($prodIds, ['1', '3', '5', '10']), 'standard' . ($delta ? '_delta' : ''));

            //Export für WMS Lager
            $jtl->createExportFile($jtl->getProducts($prodIds, ['8']), 'wms' . ($delta ? '_delta' : ''));

            $time_end = microtime(true);

            $execution_time = ($time_end - $time_start) / 60;

            // 🟢 Notify Sentry your job has completed successfully:
            captureCheckIn(
                slug: 'bestandsabgleich-delta',
                status: CheckInStatus::ok(),
                duration: $execution_time,
                checkInId: $checkInId
            );

            $io->success('Done.' . PHP_EOL . 'Execution time: ' . $execution_time . ' minutes');
            return Command::SUCCESS;
        }
    }

    public static function GetProjectRootDir()
    {
        $dirFullPath = __DIR__;

        //PRE: $dirs = /app/public/src/Helpers
        $dirs = explode('/', $dirFullPath);

        array_pop($dirs); //remove last element in array ('Helpers')
        array_pop($dirs); //remove the next last element from array ('src')

        //POST: $dirs = /app/public
        return implode('/', $dirs);
    }
}