<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\Migrations\Main;

use Chill\MainBundle\Export\Migrator\SavedExportOptionsMigrator;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Types\Types;
use Doctrine\Migrations\AbstractMigration;

final class Version20250404123326 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Update option representation of saved exports';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE chill_main_saved_export ADD COLUMN options_backup JSONB default \'[]\'');
        $this->addSql('UPDATE chill_main_saved_export SET options_backup = options');

        $result = $this->connection->executeQuery('SELECT id, options FROM chill_main_saved_export');

        foreach ($result->iterateAssociative() as $row) {
            $options = json_decode((string) $row['options'], true, 512, JSON_THROW_ON_ERROR);
            $this->addSql(
                'UPDATE chill_main_saved_export SET options = :new_options WHERE id = :id',
                ['id' => $row['id'], 'new_options' => SavedExportOptionsMigrator::migrate($options)],
                ['id' => Types::STRING, 'new_options' => Types::JSON],
            );
        }

    }

    public function down(Schema $schema): void
    {
        $this->addSql('UPDATE chill_main_saved_export SET options = options_backup');
        $this->addSql('ALTER TABLE chill_main_saved_export DROP COLUMN options_backup');
    }
}
