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

/**
 * Fix lines in chill_person_person_center_history for people created before the introduction of the createdAt column.
 *
 * This class represents a migration for fixing lines in the 'chill_person_person_center_history' table.
 *
 * It updates the 'startdate' column for people created before the introduction
 * of the 'createdAt' column, and set it at the first activity date. This migration is irreversible.
 */
final class Version20231207221700 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Fix lines in chill_person_person_center_history for people created before the introduction of the createdAt column';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('WITH first_history_line AS (SELECT *
                            FROM (SELECT id,
                                         person_id,
                                         startdate,
                                         rank() OVER (PARTITION BY person_id ORDER BY startdate ASC, id ASC) AS r
                                  FROM chill_person_person_center_history) AS sk
                            WHERE sk.r = 1),
     first_activity AS (SELECT *
                        FROM (SELECT id, date, person_id, rank() OVER (PARTITION BY person_id ORDER BY date ASC, id ASC) AS r
                              FROM activity
                              WHERE person_id IS NOT NULL) sq
                        WHERE sq.r = 1)
UPDATE chill_person_person_center_history cppch SET startdate=first_activity.date
FROM first_history_line, first_activity
WHERE
    first_history_line.id = cppch.id
    AND first_activity.person_id = cppch.person_id
    AND first_activity.date < first_history_line.startDate');
    }

    public function down(Schema $schema): void
    {
        $this->throwIrreversibleMigrationException();
    }
}
