<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Doctrine\Migrations;

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

final class Version20260604102000 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Renomme les index d audit SocialNetwork.';
    }

    public function up(Schema $schema): void
    {
        $this->renameIndex('type_ec72cdd27610ca5fe29fdd7195ddd55f_idx', 'type_693f8b48fff327392e851446631d21d6_idx');
        $this->renameIndex('object_id_ec72cdd27610ca5fe29fdd7195ddd55f_idx', 'object_id_693f8b48fff327392e851446631d21d6_idx');
        $this->renameIndex('discriminator_ec72cdd27610ca5fe29fdd7195ddd55f_idx', 'discriminator_693f8b48fff327392e851446631d21d6_idx');
        $this->renameIndex('transaction_hash_ec72cdd27610ca5fe29fdd7195ddd55f_idx', 'transaction_hash_693f8b48fff327392e851446631d21d6_idx');
        $this->renameIndex('blame_id_ec72cdd27610ca5fe29fdd7195ddd55f_idx', 'blame_id_693f8b48fff327392e851446631d21d6_idx');
        $this->renameIndex('created_at_ec72cdd27610ca5fe29fdd7195ddd55f_idx', 'created_at_693f8b48fff327392e851446631d21d6_idx');
    }

    public function down(Schema $schema): void
    {
        $this->renameIndex('type_693f8b48fff327392e851446631d21d6_idx', 'type_ec72cdd27610ca5fe29fdd7195ddd55f_idx');
        $this->renameIndex('object_id_693f8b48fff327392e851446631d21d6_idx', 'object_id_ec72cdd27610ca5fe29fdd7195ddd55f_idx');
        $this->renameIndex('discriminator_693f8b48fff327392e851446631d21d6_idx', 'discriminator_ec72cdd27610ca5fe29fdd7195ddd55f_idx');
        $this->renameIndex('transaction_hash_693f8b48fff327392e851446631d21d6_idx', 'transaction_hash_ec72cdd27610ca5fe29fdd7195ddd55f_idx');
        $this->renameIndex('blame_id_693f8b48fff327392e851446631d21d6_idx', 'blame_id_ec72cdd27610ca5fe29fdd7195ddd55f_idx');
        $this->renameIndex('created_at_693f8b48fff327392e851446631d21d6_idx', 'created_at_ec72cdd27610ca5fe29fdd7195ddd55f_idx');
    }

    private function renameIndex(string $from, string $to): void
    {
        $this->addSql(sprintf(<<<'SQL'
DO $$
BEGIN
    IF to_regclass('public.%1$s') IS NOT NULL
        AND to_regclass('public.%2$s') IS NULL THEN
        ALTER INDEX %1$s RENAME TO %2$s;
    END IF;
END $$;
SQL, $from, $to));
    }
}
