<?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 Chill\MainBundle\Entity\Center;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Add a center to class person.
 */
class Version20150607231010 extends AbstractMigration
{
    public function down(Schema $schema): void
    {
        $this->abortIf(
            'postgresql' !== $this->connection->getDatabasePlatform()->getName(),
            'Migration can only be executed safely on \'postgresql\'.'
        );

        $this->addSql('ALTER TABLE Person DROP CONSTRAINT FK_person_center');
        $this->addSql('DROP INDEX IDX_person_center');
        $this->addSql('ALTER TABLE Person DROP center_id');
    }

    public function getDescription(): string
    {
        return 'Add a center on the person entity. The default center is the first '
        .'recorded.';
    }

    public function up(Schema $schema): void
    {
        $this->abortIf(
            'postgresql' !== $this->connection->getDatabasePlatform()->getName(),
            'Migration can only be executed safely on \'postgresql\'.'
        );

        $this->addSql('ALTER TABLE person ADD center_id INT');

        // retrieve center for setting a default center
        $stmt = $this->connection->executeQuery('SELECT id FROM centers ORDER BY id ASC LIMIT 1');
        $center = $stmt->fetchOne();

        if (false !== $center) {
            $defaultCenterId = $center['id'];
        }

        if (isset($defaultCenterId)) {
            $this->addSql('UPDATE person SET center_id = :id', ['id' => $defaultCenterId]);
        }

        // this will fail if a person is defined, which should not happen any more at this
        // time of writing (2021-11-09)
        $this->addSql('ALTER TABLE person ALTER center_id SET NOT NULL');
        $this->addSql('ALTER TABLE person '
                .'ADD CONSTRAINT FK_person_center FOREIGN KEY (center_id) '
                .'REFERENCES centers (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('CREATE INDEX IDX_person_center ON person (center_id)');
    }
}
