<?php

declare(strict_types=1);

namespace D3\DecodeMigrations\migration\data;

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

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20240318163727 extends AbstractMigration
{
    public function getDescription() : string
    {
        return 'decode / encode configuration columns';
    }

    /**
     * @throws Exception
     */
    public function up(Schema $schema) : void
    {
        $this->skipIf($this->connection->getDatabasePlatform() instanceof MySQL80Platform, 'Config values can\'t decoded on MySQL 8');

        $this->connection->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');

        $table = $schema->getTable('oxconfig');
        $column = $table->getColumn('oxvarvalue');

        $this->skipIf(!$column->getType() instanceof BlobType, 'Config values are already decoded');

        $this->addSql('ALTER TABLE oxconfig ADD COLUMN `OXVARVALUE_UNENC` text;');
        $this->addSql("UPDATE oxconfig SET `OXVARVALUE_UNENC` = DECODE(OXVARVALUE, '".Config::DEFAULT_CONFIG_KEY."') WHERE 1;");
        $this->addSql('ALTER TABLE oxconfig MODIFY COLUMN `OXVARVALUE` text;');
        $this->addSql("UPDATE oxconfig SET `OXVARVALUE` = `OXVARVALUE_UNENC` WHERE 1;");
        $this->addSql('ALTER TABLE oxconfig DROP COLUMN `OXVARVALUE_UNENC`;');
    }

    public function down(Schema $schema): void
    {
        $this->skipIf($this->connection->getDatabasePlatform() instanceof MySQL80Platform, 'Config values can\'t encoded on MySQL 8');

        $this->connection->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');

        $table = $schema->getTable('oxconfig');
        $column = $table->getColumn('oxvarvalue');

        $this->skipIf($column->getType() instanceof BlobType, 'Config values are already encoded');

        $this->addSql( 'ALTER TABLE oxconfig ADD COLUMN `OXVARVALUE_ENC` text;' );
        $this->addSql( "UPDATE oxconfig SET `OXVARVALUE_ENC` = ENCODE(OXVARVALUE, '" . Config::DEFAULT_CONFIG_KEY . "') WHERE 1;" );
        $this->addSql( 'ALTER TABLE oxconfig MODIFY COLUMN `OXVARVALUE` mediumblob;' );
        $this->addSql( "UPDATE oxconfig SET `OXVARVALUE` = `OXVARVALUE_ENC` WHERE 1;" );
        $this->addSql( 'ALTER TABLE oxconfig DROP COLUMN `OXVARVALUE_ENC`;' );
    }

    public function isTransactional(): bool
    {
        return true;
    }
}