<?php

namespace Ecoyn\Setup\Console;

use QUI;
use QUI\InstallationWizard\ProviderHandler;

/**
 * Execute the QUIQQER installation wizard
 *
 * @author  www.pcsg.de (Jan Wennrich)
 * @licence For copyright and license information, please view the /README.md
 */
final class InstallationWizard extends QUI\System\Console\Tool
{
    public function __construct()
    {
        $this->systemTool = true;
        $this->setName('ecoyn:installation-wizard')
            ->setDescription('Execute the ECOYN installation wizard with data from a given preset file')
            ->addArgument(
                'preset-file',
                'Path to a JSON file that contains the data to use for the wizard',
                false,
                false
            );
    }

    public function execute(): void
    {
        $presetFile = $this->getArgument('preset-file');

        if (!is_string($presetFile) || $presetFile === '' || !file_exists($presetFile)) {
            $this->writeLn('Error: The preset file does not exist.', 'red');
            return;
        }

        $presetDataAsJsonString = file_get_contents($presetFile);

        if ($presetDataAsJsonString === false) {
            $this->writeLn("Error: Could not read preset file '$presetFile'.", 'red');
            return;
        }

        $presetData = json_decode($presetDataAsJsonString, true);

        if (!is_array($presetData)) {
            $this->writeLn("Error: Could not decode JSON in preset file '$presetFile'.", 'red');
            return;
        }

        $SetupProvider = new \Ecoyn\Setup\SetupProvider();

        // Execute the wizard with the preset data
        $SetupProvider->execute($presetData);

        // Mark the wizard as done
        ProviderHandler::setProviderStatus($SetupProvider, ProviderHandler::STATUS_SET_UP_DONE);

        // Finish the setup wizard
        $SetupProvider->finish(); // @phpstan-ignore method.resultUnused
        (new \Ecoyn\Setup\SetupFinish())->execute();

        $this->writeLn("ECOYN installation wizard was successfully executed.", 'green');
    }
}
