<?php
namespace Neos\Flow\Persistence\Doctrine\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

class Version20200723103317 extends AbstractMigration
{
    public function up(Schema $schema): void
    {
        $this->abortIf(
            $this->connection->getDatabasePlatform()->getName() != 'mysql',
            'Migration can only be executed safely on "mysql".'
        );

        // Auto-naming of keys has apparently changed at some point in the past.
        // Thus, the index could have any of these names.
        $table = 'newland_toubiz_sync_neos_domain_model_externalid';
        $possibleIndexNames = [
            'newland_toubiz_sync_neos_external_id_ident',
            'UNIQ_B3D281D98CDE5729BF396750',
        ];

        foreach ($possibleIndexNames as $name) {
            if (!$this->keyExists($table, $name)) {
                continue;
            }
            $this->addSql(sprintf('DROP INDEX %s ON %s', $name, $table));
        }
    }

    public function down(Schema $schema): void
    {
        $this->abortIf(
            $this->connection->getDatabasePlatform()->getName() != 'mysql',
            'Migration can only be executed safely on "mysql".'
        );

        $this->addSql(
            'CREATE INDEX newland_toubiz_sync_neos_external_id_ident ON newland_toubiz_sync_neos_domain_model_externalid (type, id)'
        );
    }

    private function keyExists(string $tableName, string $keyName): bool
    {
        foreach ($this->sm->listTableDetails($tableName)->getIndexes() as $index) {
            if ($index->getName() === $keyName) {
                return true;
            }
        }
        return false;
    }
}
