<?php

declare(strict_types=1);

/** @noinspection PhpUnused */

namespace App\Commands\Doctrine;

use App\Service\Doctrine\SchemaValidation\DiffTypeEnum;
use App\Service\Doctrine\SchemaValidation\SchemaSnippetsMaker;
use App\Service\Doctrine\SchemaValidation\SchemaValidationService;
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;

/**
 * Valide le schéma Doctrine en le comparant à la V1.
 *
 * @see https://ressources-opentalent.atlassian.net/wiki/spaces/DEV/pages/240551231/V+rifier+le+sch+ma+Doctrine+de+la+V2+et+g+n+rer+les+entit+s+et+propri+t+s+manquantes
 */
#[AsCommand(
    name: 'ot:schema:validate',
    description: 'Compare le schema doctrine de la V2 à celui de la V1'
)]
class SchemaValidateCommand extends Command
{
    public function __construct(
        private readonly SchemaValidationService $schemaValidationService,
        private readonly SchemaSnippetsMaker $schemaSnippetsMaker,
    ) {
        parent::__construct();
    }

    /**
     * Configures the command.
     */
    protected function configure(): void
    {
        $this->addOption(
            'filter',
            null,
            InputOption::VALUE_OPTIONAL,
            "Filter the type of difference to display (ex: 'MISSING_PROPERTY')."
        );
        $this->addOption(
            'snippets',
            null,
            InputOption::VALUE_NONE,
            'Make snippets of the missing classes and fields'
        );
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $filter = $input->getOption('filter') ? DiffTypeEnum::from($input->getOption('filter')) : null;

        $diff = $this->schemaValidationService->validateSchema($filter);

        $csv = $this->schemaValidationService->formatToCsv($diff);

        if (empty($csv)) {
            $output->writeln('No difference found');

            return 0;
        }

        foreach ($csv as $line) {
            $output->writeln($line);
        }

        $output->writeln(count($csv).' differences found');

        if ($input->getOption('snippets')) {
            $this->schemaSnippetsMaker->makeSnippets($diff);
            $output->writeln('Snippets generated');
        }

        return 0;
    }
}
