<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Doctrine\Migrations;

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

final class Version20260720100000 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Restore the client email group mapping identifier sequence after legacy schema normalization.';
    }

    public function up(Schema $schema): void
    {
        if (!$this->tableExists()) {
            return;
        }

        $this->addSql('CREATE SEQUENCE IF NOT EXISTS client_email_group_mapping_id_seq');
        $this->addSql('ALTER SEQUENCE client_email_group_mapping_id_seq OWNED BY client_email_group_mapping.id');
        $this->addSql("ALTER TABLE client_email_group_mapping ALTER COLUMN id SET DEFAULT nextval('client_email_group_mapping_id_seq'::regclass)");
        $this->addSql(<<<'SQL'
            SELECT setval(
                'client_email_group_mapping_id_seq',
                COALESCE((SELECT MAX(id) FROM client_email_group_mapping), 1),
                EXISTS (SELECT 1 FROM client_email_group_mapping)
            )
            SQL);
    }

    public function down(Schema $schema): void
    {
        if ($this->tableExists()) {
            $this->addSql('ALTER TABLE client_email_group_mapping ALTER COLUMN id DROP DEFAULT');
        }
    }

    private function tableExists(): bool
    {
        return (bool) $this->connection->fetchOne(
            "SELECT to_regclass('public.client_email_group_mapping') IS NOT NULL"
        );
    }
}
