<?php declare(strict_types=1);
/**
 * This file is part of the SplendidBear Websites' projects.
 *
 * Copyright (c) 2026 @ www.splendidbear.org
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Migrations;

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

/**
 * Class Version20260420064216
 *
 * Realign each PostgreSQL IDENTITY counter to MAX(id)+1.
 *
 * Required because Version20260419195925 converted the ID columns from sequences to
 * GENERATED BY DEFAULT AS IDENTITY (DBAL 4 / ORM 3 default), but PostgreSQL starts
 * the new IDENTITY counter at 1 instead of inheriting the old sequence's last_value.
 * The first INSERT on every table thus produced a duplicate-key collision.
 *
 * @package  App\Migrations
 * @author   Lang <https://www.splendidbear.org>
 * @category Class
 * @license  https://www.gnu.org/licenses/lgpl-3.0.en.html GNU Lesser General Public License
 * @link     www.splendidbear.org
 * @since    2026. 04. 20.
 */
final class Version20260420064216 extends AbstractMigration
{
    private const TABLES = [
        'played_game',
        'grid',
        'grid_row',
        'step',
        'app_user',
        'app_webauthn_credential',
        'gamer',
        'contact_messages',
    ];

    public function getDescription(): string
    {
        return 'Realign IDENTITY counters to MAX(id)+1 after the sequence-to-identity conversion.';
    }

    public function up(Schema $schema): void
    {
        foreach (self::TABLES as $table) {
            $this->addSql(sprintf(
                "SELECT setval(pg_get_serial_sequence('%s', 'id'), COALESCE((SELECT MAX(id) FROM %s), 0) + 1, false)",
                $table,
                $table,
            ));
        }
    }

    public function down(Schema $schema): void
    {
        $this->throwIrreversibleMigrationException('Identity counter realignment cannot be reversed safely.');
    }
}
