<?php

/*
 * This file is part of the VitiCore 2.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Command;

use League\Flysystem\FilesystemOperator;
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\Finder\Finder;

#[AsCommand(name: 'viti-core:upload-stubs')]
final class UploadStubsCommand extends Command
{
    public function __construct(
        private readonly FilesystemOperator $imageFilesystem,
    ) {
        parent::__construct();
    }

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

        $io->comment('Copy image product to public directory…');

        $stubsDir = \dirname(__DIR__, 4).'/fixtures/stubs';

        $finder = Finder::create()
            ->files()
            ->in($stubsDir);

        foreach ($finder as $file) {
            $relativePath = str_replace('\\', '/', $file->getRelativePathname());

            if ($this->imageFilesystem->fileExists($relativePath)) {
                $io->comment($relativePath.' is already uploaded');
                continue;
            }

            $io->comment('Uploading '.$relativePath.'…');

            $contents = file_get_contents((string) $file->getRealPath());

            if (false === $contents) {
                $io->warning('Unable to read: '.$relativePath);
                continue;
            }

            $this->imageFilesystem->write($relativePath, $contents);
        }

        $io->success('Done.');

        return Command::SUCCESS;
    }
}
