<?php /** @noinspection PhpUnused */

namespace App\Commands\Doctrine;

use App\Service\Utils\Path;
use Doctrine\Bundle\DoctrineBundle\Command\Proxy\UpdateSchemaDoctrineCommand;
use Doctrine\ORM\Tools\SchemaTool;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

/**
 * Overrides the default doctrine:schema:update command
 */
class SchemaUpdateCommand extends UpdateSchemaDoctrineCommand
{
    protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas, SymfonyStyle $ui): ?int
    {
        $output->writeln('-- Executing pre-update scripts');

        // Lists schema extensions scripts in the '/sql/schema-extensions' dir
        $schemaExtensionsDir = Path::join(Path::getProjectDir(), 'sql', 'schema-extensions');
        $scripts = Path::list($schemaExtensionsDir, '*.sql');
        sort($scripts);

        // Execute those scripts in alphabetical order
        $em = $this->getEntityManager($input);
        $conn = $em->getConnection();

        foreach ($scripts as $script) {
            $sql = Path::read($script);
            $conn->executeQuery($sql);
        }

        $output->writeln(sprintf('-- Database successfully updated, %s scripts executed', count($scripts)));

        throw new \RuntimeException('<!> Operation interrupted: use the d:s:u command on the current version to update the DB tables');
//        parent::executeSchemaCommand($input, $output, $schemaTool, $metadatas, $ui);
    }
}
