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

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

final class Version20241202173942 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add a unique constraint on the storedobject linked to an activity';
    }

    public function up(Schema $schema): void
    {
        $this->addSql(
            'WITH duplicate_activities AS (
                SELECT storedobject_id, array_agg(activity_id ORDER BY activity_id DESC) AS activities
                FROM activity_storedobject
                GROUP BY storedobject_id
                HAVING count(*) > 1
            )
            DELETE FROM activity_storedobject
            WHERE activity_id IN (
                SELECT unnest(activities[2:]) -- Keep the highest ID, delete the rest
                FROM duplicate_activities
            );'
        );
        $this->addSql('CREATE UNIQUE INDEX unique_storedobject_id ON activity_storedobject (storedobject_id)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('DROP INDEX IF EXISTS unique_storedobject_id');
    }
}
