<?php

declare(strict_types=1);

/** @noinspection PhpUnused */

namespace App\Commands\Doctrine;

use App\Service\Utils\PathUtils;
use Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand;
use Doctrine\ORM\Tools\Console\EntityManagerProvider;
use Doctrine\ORM\Tools\SchemaTool;
use Path\Path;
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 UpdateCommand
{
    public static function getDefaultName(): string
    {
        return 'doctrine:schema:update';
    }

    public function __construct(
        private readonly EntityManagerProvider $entityManagerProvider,
    ) {
        parent::__construct($this->entityManagerProvider);
    }

    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 = PathUtils::join(PathUtils::getProjectDir(), 'sql', 'schema-extensions');

        $schemaExtensionsDir = (new Path(PathUtils::getProjectDir()))->append('sql', 'schema-extensions');

        $scripts = $schemaExtensionsDir->glob('*.sql');
        sort($scripts);

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

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

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

        $output->writeln('<!> Operation interrupted: use the d:s:u command on the current version to update the DB tables');

        //        parent::executeSchemaCommand($input, $output, $schemaTool, $metadatas, $ui);
        return 0;
    }
}
