<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Doctrine\Migrations;

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

final class Version20260723220000 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Restreint chaque coupon de relance panier au panier pour lequel il a été créé.';
    }

    public function up(Schema $schema): void
    {
        $this->abortIf(!$this->connection->getDatabasePlatform() instanceof PostgreSQLPlatform, 'Cette migration nécessite PostgreSQL.');

        $this->addSql('ALTER TABLE cart_promo ADD restricted_cart_id UUID DEFAULT NULL');
        $this->addSql(<<<'SQL'
            UPDATE cart_promo promo
            SET restricted_cart_id = reminder.cart_id
            FROM marketing_abandoned_cart_reminder reminder
            WHERE reminder.promo_id = promo.id
            SQL);
        $this->addSql('CREATE INDEX IDX_EFF9F7F3F8CCE7C0 ON cart_promo (restricted_cart_id)');
        $this->addSql('ALTER TABLE cart_promo ADD CONSTRAINT FK_CART_PROMO_RESTRICTED_CART FOREIGN KEY (restricted_cart_id) REFERENCES cart_cart (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql("COMMENT ON COLUMN cart_promo.restricted_cart_id IS '(DC2Type:uuid)'");
    }

    public function down(Schema $schema): void
    {
        $this->abortIf(!$this->connection->getDatabasePlatform() instanceof PostgreSQLPlatform, 'Cette migration nécessite PostgreSQL.');

        $this->addSql('ALTER TABLE cart_promo DROP CONSTRAINT FK_CART_PROMO_RESTRICTED_CART');
        $this->addSql('DROP INDEX IDX_EFF9F7F3F8CCE7C0');
        $this->addSql('ALTER TABLE cart_promo DROP restricted_cart_id');
    }
}
