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

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

final class Version20231128114959 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add unique index on participation and drop column participation::lastUpdate';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('UPDATE chill_event_participation SET updatedAt=lastupdate WHERE updatedat IS NULL');
        $this->addSql('ALTER TABLE chill_event_participation DROP lastupdate');
        $this->addSql('WITH ordering AS (SELECT id, event_id, person_id, rank() OVER (PARTITION BY event_id, person_id ORDER BY id DESC) as ranked FROM chill_event_participation),
     not_last AS (SELECT * FROM ordering where ranked > 1)
     DELETE FROM chill_event_participation WHERE id IN (select id FROM not_last)');
        $this->addSql('CREATE UNIQUE INDEX chill_event_participation_event_person_unique_idx ON chill_event_participation (event_id, person_id)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('DROP INDEX chill_event_participation_event_person_unique_idx');
        $this->addSql('ALTER TABLE chill_event_participation ADD lastupdate TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL');
        $this->addSql('UPDATE chill_event_participation set lastupdate = updatedat');
    }
}
