<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Installer\Migration;

use Doctrine\DBAL\Schema\Schema;

final class Version1_1_0 extends AbstractMigration
{
    public function getVersion(): string
    {
        return '1.1.0';
    }

    public function up(Schema $schema): void
    {
        $this->dropCarriersForeignKey($schema);
    }

    /**
     * Using non-unique or partial keys as foreign keys was deprecated and disabled by default in MySQL 8.4.
     * We drop an existing key to avoid potential issues with MySQL upgrade.
     */
    private function dropCarriersForeignKey(Schema $schema): void
    {
        if (!$schema->hasTable($tableName = $this->prefixTableName('gls_poland_carrier'))) {
            return;
        }

        $table = $schema->getTable($tableName);
        $carrierTableName = $this->prefixTableName('carrier');

        foreach ($table->getForeignKeys() as $foreignKey) {
            if ($carrierTableName !== $foreignKey->getForeignTableName()) {
                continue;
            }

            $table->removeForeignKey($foreignKey->getName());

            return;
        }
    }
}
