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

/**
 * Add linkedToThirdParty field to Address.
 */
final class Version20210505153727 extends AbstractMigration
{
    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE chill_main_address DROP CONSTRAINT FK_165051F6114B8DD9');
        $this->addSql('DROP INDEX IDX_165051F6114B8DD9');
        $this->addSql('ALTER TABLE chill_main_address DROP linkedToThirdParty_id');
        $this->addSql('DROP TABLE IF EXISTS chill_main_address_legacy');
        $this->addSql('
            UPDATE chill_main_address
            SET validto = null;
        ');
    }

    public function getDescription(): string
    {
        return 'Add linkedToThirdParty field to Address';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE chill_main_address ADD linkedToThirdParty_id INT DEFAULT NULL');
        $this->addSql('ALTER TABLE chill_main_address ADD CONSTRAINT FK_165051F6114B8DD9 FOREIGN KEY (linkedToThirdParty_id) REFERENCES chill_3party.third_party (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('CREATE INDEX IDX_165051F6114B8DD9 ON chill_main_address (linkedToThirdParty_id)');
        $this->addSql('
            CREATE TABLE chill_main_address_legacy AS
            TABLE chill_main_address;
        ');
        $this->addSql('
            WITH hydrated_addresses AS (
                SELECT *, rank() OVER (PARTITION BY pa_a.person_id ORDER BY validfrom, id)
                FROM chill_main_address AS aa JOIN chill_person_persons_to_addresses AS pa_a ON aa.id = pa_a.address_id
            )
            UPDATE chill_main_address AS b
            SET validto = (
                SELECT validfrom
                FROM hydrated_addresses
                WHERE hydrated_addresses.id = (
                    SELECT a1.id
                    FROM hydrated_addresses AS a1 JOIN hydrated_addresses AS a2 ON a2.person_id = a1.person_id AND a2.rank = (a1.rank-1)
                    WHERE a2.id = b.id
                )
            );
        ');
    }
}
