<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Doctrine\Migrations;

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

final class Version20260529100000 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Ajoute la configuration Meta Conversions API par pixel.';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE shop_shop_config ADD COLUMN IF NOT EXISTS meta_conversions_pixel_configs JSON DEFAULT \'[]\'');
        $this->addSql(
            <<<'SQL'
            UPDATE shop_shop_config
            SET meta_conversions_pixel_configs = json_build_array(json_build_object(
                'pixelId', facebook_pixel_ids->>0,
                'accessToken', meta_conversions_access_token
            ))
            WHERE meta_conversions_access_token IS NOT NULL
                AND meta_conversions_access_token <> ''
                AND facebook_pixel_ids IS NOT NULL
                AND json_array_length(facebook_pixel_ids) > 0
                AND (
                    meta_conversions_pixel_configs IS NULL
                    OR json_array_length(meta_conversions_pixel_configs) = 0
                )
            SQL,
        );
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE shop_shop_config DROP COLUMN IF EXISTS meta_conversions_pixel_configs');
    }
}
