<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Doctrine\Migrations;

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

final class Version20260519113000 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Répare la séquence PostgreSQL des items de collection produit.';
    }

    public function up(Schema $schema): void
    {
        $this->addSql(<<<'SQL'
DO $$
BEGIN
    IF to_regclass('public.product_collection_item') IS NOT NULL THEN
        IF to_regclass('public.product_collection_item_id_seq') IS NULL THEN
            CREATE SEQUENCE product_collection_item_id_seq INCREMENT BY 1 MINVALUE 1 START 1;
        END IF;

        ALTER TABLE product_collection_item
            ALTER COLUMN id SET DEFAULT NEXTVAL('product_collection_item_id_seq');

        ALTER SEQUENCE product_collection_item_id_seq
            OWNED BY product_collection_item.id;

        PERFORM setval(
            'product_collection_item_id_seq',
            GREATEST((SELECT COALESCE(MAX(id), 0) FROM product_collection_item), 1),
            (SELECT COUNT(*) > 0 FROM product_collection_item)
        );
    END IF;
END
$$;
SQL);
    }

    public function down(Schema $schema): void
    {
        // no-op
    }
}
