<?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 Version20240123161457 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Store closing motive when closing a course';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE chill_person_accompanying_period_step_history ADD closingMotive_id INT DEFAULT NULL');
        $this->addSql('ALTER TABLE chill_person_accompanying_period_step_history ADD CONSTRAINT FK_84D514AC504CB38D FOREIGN KEY (closingMotive_id) REFERENCES chill_person_accompanying_period_closingmotive (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('ALTER TABLE chill_person_accompanying_period_step_history ADD CONSTRAINT FK_84D514AC65FF1AEC FOREIGN KEY (updatedBy_id) REFERENCES users (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql(<<<'EOF'
            WITH last_step AS (
                SELECT * FROM (
                    SELECT *, rank() OVER (partition by period_id ORDER BY startdate DESC, id DESC) AS r FROM chill_person_accompanying_period_step_history cpapsh
                ) as sq
                WHERE r = 1
            )
            UPDATE chill_person_accompanying_period_step_history
            SET closingMotive_id = chill_person_accompanying_period.closingmotive_id
            FROM last_step, chill_person_accompanying_period
            WHERE last_step.period_id = chill_person_accompanying_period_step_history.period_id AND chill_person_accompanying_period.id = chill_person_accompanying_period_step_history.period_id
                AND last_step.step = 'CLOSED';
            EOF);
        $this->addSql('CREATE INDEX IDX_84D514AC504CB38D ON chill_person_accompanying_period_step_history (closingMotive_id)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE chill_person_accompanying_period_step_history DROP CONSTRAINT FK_84D514AC504CB38D');
        $this->addSql('ALTER TABLE chill_person_accompanying_period_step_history DROP CONSTRAINT FK_84D514AC65FF1AEC');
        $this->addSql('DROP INDEX IDX_84D514AC504CB38D');
        $this->addSql('ALTER TABLE chill_person_accompanying_period_step_history DROP closingMotive_id');
    }
}
