<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Doctrine\Migrations;

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

final class Version20260529113000 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Déplace le contexte Matomo checkout dans marketing_attribution.';
    }

    public function up(Schema $schema): void
    {
        $this->addSql(<<<'SQL'
DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'public'
          AND table_name = 'cart_cart_checkout'
          AND column_name = 'matomo_visitor_id'
    ) THEN
        UPDATE cart_cart_checkout
        SET marketing_attribution = (
            COALESCE(marketing_attribution::jsonb, '{}'::jsonb)
            || jsonb_build_object(
                'matomo',
                COALESCE(marketing_attribution::jsonb -> 'matomo', '{}'::jsonb)
                || jsonb_strip_nulls(jsonb_build_object(
                    'visitor_id', matomo_visitor_id,
                    'user_agent', matomo_user_agent,
                    'url', matomo_url,
                    'referrer', matomo_referrer
                ))
            )
        )::json
        WHERE matomo_visitor_id IS NOT NULL
           OR matomo_user_agent IS NOT NULL
           OR matomo_url IS NOT NULL
           OR matomo_referrer IS NOT NULL;
    END IF;
END $$;
SQL);

        $this->addSql('ALTER TABLE cart_cart_checkout DROP COLUMN IF EXISTS matomo_visitor_id');
        $this->addSql('ALTER TABLE cart_cart_checkout DROP COLUMN IF EXISTS matomo_user_agent');
        $this->addSql('ALTER TABLE cart_cart_checkout DROP COLUMN IF EXISTS matomo_url');
        $this->addSql('ALTER TABLE cart_cart_checkout DROP COLUMN IF EXISTS matomo_referrer');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE cart_cart_checkout ADD COLUMN IF NOT EXISTS matomo_visitor_id VARCHAR(16) DEFAULT NULL');
        $this->addSql('ALTER TABLE cart_cart_checkout ADD COLUMN IF NOT EXISTS matomo_user_agent VARCHAR(512) DEFAULT NULL');
        $this->addSql('ALTER TABLE cart_cart_checkout ADD COLUMN IF NOT EXISTS matomo_url TEXT DEFAULT NULL');
        $this->addSql('ALTER TABLE cart_cart_checkout ADD COLUMN IF NOT EXISTS matomo_referrer TEXT DEFAULT NULL');

        $this->addSql(<<<'SQL'
UPDATE cart_cart_checkout
SET matomo_visitor_id = COALESCE(matomo_visitor_id, marketing_attribution::jsonb #>> '{matomo,visitor_id}'),
    matomo_user_agent = COALESCE(matomo_user_agent, marketing_attribution::jsonb #>> '{matomo,user_agent}'),
    matomo_url = COALESCE(matomo_url, marketing_attribution::jsonb #>> '{matomo,url}'),
    matomo_referrer = COALESCE(matomo_referrer, marketing_attribution::jsonb #>> '{matomo,referrer}')
WHERE marketing_attribution::jsonb ? 'matomo';
SQL);
    }
}
