<?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 Version20260723210000 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Restreint les coupons de relance panier au groupe de prix choisi dans leur règle.';
    }

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

        $this->addSql('ALTER TABLE marketing_abandoned_cart_rule ADD price_group_id UUID DEFAULT NULL');
        $this->addSql(<<<'SQL'
            UPDATE marketing_abandoned_cart_rule
            SET price_group_id = (
                SELECT id
                FROM product_price_group
                WHERE by_default = TRUE
                ORDER BY position ASC NULLS LAST, id ASC
                LIMIT 1
            )
            SQL);
        $this->addSql('ALTER TABLE marketing_abandoned_cart_rule ALTER price_group_id SET NOT NULL');
        $this->addSql('CREATE INDEX IDX_3511F1359CE2E250 ON marketing_abandoned_cart_rule (price_group_id)');
        $this->addSql('ALTER TABLE marketing_abandoned_cart_rule ADD CONSTRAINT FK_3511F1359CE2E250 FOREIGN KEY (price_group_id) REFERENCES product_price_group (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql(<<<'SQL'
            INSERT INTO promo_product_price_group (promo_id, product_price_group_id)
            SELECT reminder.promo_id, rule.price_group_id
            FROM marketing_abandoned_cart_reminder reminder
            INNER JOIN marketing_abandoned_cart_rule rule ON rule.id = reminder.rule_id
            WHERE reminder.promo_id IS NOT NULL
            ON CONFLICT DO NOTHING
            SQL);
    }

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

        $this->addSql(<<<'SQL'
            DELETE FROM promo_product_price_group promo_group
            USING marketing_abandoned_cart_reminder reminder, marketing_abandoned_cart_rule rule
            WHERE reminder.promo_id = promo_group.promo_id
              AND rule.id = reminder.rule_id
              AND rule.price_group_id = promo_group.product_price_group_id
            SQL);
        $this->addSql('ALTER TABLE marketing_abandoned_cart_rule DROP CONSTRAINT FK_3511F1359CE2E250');
        $this->addSql('DROP INDEX IDX_3511F1359CE2E250');
        $this->addSql('ALTER TABLE marketing_abandoned_cart_rule DROP price_group_id');
    }
}
