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

final class Version20230628152138 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'An accompanying period cannot have both a locaiton on a period and on an address';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('UPDATE chill_person_accompanying_period SET addresslocation_id = NULL
                                        where personlocation_id IS NOT NULL AND addresslocation_id IS NOT NULL');
        $this->addSql('INSERT INTO chill_person_accompanying_period_location_history
            (id, period_id, startdate, enddate, createdat, personlocation_id, addresslocation_id, createdby_id)
            SELECT nextval(\'chill_person_accompanying_period_location_history_id_seq\'), period_id, startdate, startdate, now(), null, addresslocation_id, null
            FROM chill_person_accompanying_period_location_history
            WHERE personlocation_id IS NOT NULL AND addresslocation_id IS NOT NULL
            ');
        $this->addSql('UPDATE chill_person_accompanying_period_location_history SET addresslocation_id = NULL WHERE addresslocation_id IS NOT NULL AND personlocation_id IS NOT NULL');

        $this->addSql('ALTER TABLE chill_person_accompanying_period ADD CONSTRAINT location_check CHECK (personlocation_id IS NULL OR addresslocation_id IS NULL)');
        $this->addSql('ALTER TABLE chill_person_accompanying_period_location_history ADD CONSTRAINT location_check CHECK (personlocation_id IS NULL OR addresslocation_id IS NULL)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE chill_person_accompanying_period DROP CONSTRAINT location_check');
        $this->addSql('ALTER TABLE chill_person_accompanying_period_location_history DROP CONSTRAINT location_check');
    }
}
