<?php

namespace App\OgBootBundle\Command;

use App\OgBootBundle\Service\CurlRequestService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\HttpClient\HttpClient;
use Psr\Log\LoggerInterface;
use Exception;

class OgLiveInstallCommand extends Command
{
    protected static $defaultName = 'oglive:install';
    private $curlRequestService;
    private $httpClient;
    private $logger;
    private $ogCoreApiUrl;

    public function __construct(
        CurlRequestService $curlRequestService,
        HttpClientInterface $httpClient,
        LoggerInterface $logger,
        string $ogCoreApiUrl
    ) {
        parent::__construct();
        $this->curlRequestService = $curlRequestService;
        $this->httpClient = HttpClient::create([
            'verify_peer' => false, // Ignorar la verificación del certificado SSL
            'verify_host' => false, // Ignorar la verificación del nombre del host
        ]);
        $this->logger = $logger;
        $this->ogCoreApiUrl = $ogCoreApiUrl;
    }

    protected function configure()
    {
        $this
            ->setDescription('Instala un ogLive en segundo plano')
            ->addArgument('isoUrl', InputArgument::REQUIRED, 'URL del ISO de ogLive')
            ->addArgument('transactionId', InputArgument::REQUIRED, 'ID de la transacción');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', '3000');

        $isoUrl = $input->getArgument('isoUrl');
        $transactionId = $input->getArgument('transactionId');

        // Log inicial
        $this->logger->info('Starting ogLive installation process.', [
            'transactionId' => $transactionId,
            'isoUrl' => $isoUrl,
        ]);

        try {
            // Log: Iniciando la descarga
            $this->logger->info('Initiating ISO download.', ['isoUrl' => $isoUrl]);

            // Llamada al servicio para iniciar la descarga del ISO
            $installResult = $this->curlRequestService->callOgLive("download " . escapeshellarg($isoUrl));

            // Log: Descarga completada
            $this->logger->info('ISO download completed.', [
                'transactionId' => $transactionId,
                'installResult' => $installResult,
            ]);

            // Verificación de resultado
            $exitCode = $installResult['exitCode'];
            $status = ($exitCode === 0) ? 'success' : 'failure';
            $messageText = $installResult['output']['message'] ?? 'Unknown error';

            if ($exitCode !== 0) {
                $this->logger->error('Installation failed.', [
                    'transactionId' => $transactionId,
                    'exitCode' => $exitCode,
                    'error' => $messageText,
                ]);
            } else {
                $this->logger->info('Installation completed successfully.', [
                    'transactionId' => $transactionId,
                ]);
            }

            // Preparar datos para el webhook
            $webhookData = [
                'ogCoreId' => $transactionId,
                'status' => $status,
                'code' => ($exitCode === 0) ? 200 : $exitCode,
                'message' => $messageText,
            ];

            $this->logger->info('Webhook data prepared.', ['webhookData' => $webhookData]);

            // Enviar al webhook
            $webhookUrl = "{$this->ogCoreApiUrl}/og-lives/install/webhook";
            $this->logger->info('Sending data to webhook.', ['webhookUrl' => $webhookUrl]);
            $this->notifyWebhook($webhookUrl, $webhookData);

        } catch (Exception $e) {
            // Log de error
            $this->logger->error('Installation process failed.', [
                'transactionId' => $transactionId,
                'exception' => $e->getMessage(),
            ]);

            // Enviar notificación de error al webhook
            $webhookData = [
                'ogCoreId' => $transactionId,
                'status' => 'failure',
                'code' => 500,
                'message' => $e->getMessage(),
            ];

            $webhookUrl = "{$this->ogCoreApiUrl}/og-lives/install/webhook";
            $this->logger->info('Sending error notification to webhook.', ['webhookUrl' => $webhookUrl]);
            $this->notifyWebhook($webhookUrl, $webhookData);
        }

        // Log finalización
        $this->logger->info('Installation process ended.', ['transactionId' => $transactionId]);

        return Command::SUCCESS;
    }

    private function notifyWebhook(string $webhookUrl, array $webhookData): void
    {
        try {
            $this->logger->info('Sending webhook notification.', ['webhookData' => $webhookData]);
            $this->httpClient->request('POST', $webhookUrl, [
                'headers' => [
                    'accept' => 'application/json',
                    'Content-Type' => 'application/json',
                ],
                'body' => json_encode(['webhookData' => $webhookData]),
            ]);
            $this->logger->info('Webhook notification sent successfully.', ['webhookUrl' => $webhookUrl]);
        } catch (Exception $e) {
            $this->logger->error('Error sending webhook notification.', [
                'webhookUrl' => $webhookUrl,
                'exception' => $e->getMessage(),
            ]);
        }
    }
}
