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

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

/**
 * Auto-generated Migration: Please modify to your needs! This block will be used as the migration description if getDescription() is not used.
 */
class Version20200518101954 extends AbstractMigration
{

    /**
     * @return string
     */
    public function getDescription()
    {
        return '';
    }

    /**
     * @param Schema $schema
     * @return void
     */
    public function up(Schema $schema)
    {
        // this up() migration is autogenerated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on "mysql".');

        $this->addSql('ALTER TABLE newland_toubiz_sync_neos_domain_model_article ADD sourcesystem VARCHAR(255) NOT NULL');
        $this->addSql('CREATE INDEX newland_toubiz_sync_neos_article_original_id ON newland_toubiz_sync_neos_domain_model_article (originalid)');
        $this->addSql('CREATE INDEX newland_toubiz_sync_neos_article_language_grouping ON newland_toubiz_sync_neos_domain_model_article (languagegrouping)');

        if ($this->keyExists('newland_toubiz_sync_neos_domain_model_externalid', 'UNIQ_B3D281D98CDE5729BF396750')) {
            $this->addSql('DROP INDEX UNIQ_B3D281D98CDE5729BF396750 ON newland_toubiz_sync_neos_domain_model_externalid');
        }
    }

    /**
     * @param Schema $schema
     * @return void
     */
    public function down(Schema $schema)
    {
        // this down() migration is autogenerated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on "mysql".');

        $this->addSql('ALTER TABLE newland_toubiz_sync_neos_domain_model_article DROP sourcesystem');
        $this->addSql('DROP INDEX newland_toubiz_sync_neos_article_original_id ON newland_toubiz_sync_neos_domain_model_article');
        $this->addSql('DROP INDEX newland_toubiz_sync_neos_article_language_grouping ON newland_toubiz_sync_neos_domain_model_article');
        $this->addSql('CREATE UNIQUE INDEX UNIQ_B3D281D98CDE5729BF396750 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;
    }
}
