<?php declare(strict_types=1);

namespace Newland\ToubizWidgetRendering\Utility;

use Symfony\Component\Console\Output\OutputInterface;
use Neos\Flow\Annotations as Flow;

class WebpackUtility
{

    /**
     * @var CommandRunner
     * @Flow\Inject()
     */
    protected $commandRunner;

    public function run(array $configuration, OutputInterface $output): void
    {
        $env = [
            'TAILWIND_CONFIG' => $configuration['tailwindConfig'],
            'NODE_ENV' => $configuration['buildMode'],
            'TOUBIZ_BASE_URI' => rtrim($configuration['toubizBaseUri'], '/'),
            'WIDGET_CONFIGURATION' => ($configuration['widgetConfiguration'] ?? null)
                ? json_encode($configuration['widgetConfiguration'])
                : null,
        ];

        $command = [
            'npx',
            'webpack',
            '--config=' . $configuration['webpackConfig'],
            '--output-path=' . $configuration['outputPath'],
            '--output-public-path=' . $configuration['publicPath'],
            '--entry=' . $configuration['entry'],
        ];

        foreach ($configuration['alias'] ?? [] as $from => $to) {
            $command[] = sprintf('--resolve-alias=%s=%s', $from, $to);
        }

        $this->commandRunner->timeout(600)->run($command, $output, $env);
    }
}
