<?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\Person;

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

/**
 * This migration store the cfdata using the postgresql jsonb type instead
 * of the result of the sterialization.
 */
class Version20160818113633 extends AbstractMigration
{
    /**
     * Inverse of up.
     */
    public function down(Schema $schema): void
    {
        $this->addSQL('ALTER TABLE person DROP COLUMN cfdata');
        $this->addSQL('ALTER TABLE person RENAME COLUMN cfdata_old TO cfdata');
        $this->addSql('ALTER TABLE person ALTER COLUMN cfdata SET NOT NULL');
    }

    /**
     * Make a copy of the column cfdata into the column cfdata_old. Then
     * remplace the sterialized data into a json data.
     */
    public function up(Schema $schema): void
    {
        $personIdAndCFData = $this->connection->executeQuery('SELECT id, cfdata FROM person');

        $this->addSQL('ALTER TABLE person RENAME COLUMN cfdata TO cfdata_old');
        $this->addSql('ALTER TABLE person ALTER COLUMN cfdata_old DROP NOT NULL');
        $this->addSQL('ALTER TABLE person ADD COLUMN cfdata jsonb');

        foreach ($personIdAndCFData as $person) {
            $personId = $person['id'];
            $cFDataArray = unserialize($person['cfdata']);
            $cFDataJson = json_encode($cFDataArray, JSON_THROW_ON_ERROR);
            $this->addSql(
                'UPDATE person set cfdata = :cfdatajson WHERE id = :id',
                ['cfdatajson' => $cFDataJson, 'id' => $personId]
            );
        }
    }
}
