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

/**
 * Migration fixing the automatic association of users to activities (exchanges).
 *
 * Originally, the user who created an exchange was not automatically associated
 * to it (the "TMS" column), which led to incomplete data and biased statistics.
 *
 * This migration:
 *  - retroactively associates the creator of each exchange to the corresponding
 *    activity;
 *  - flags these backfilled associations with a temporary column so it is clear
 *    they were added by this data correction and can be safely cleaned up later.
 */
final class Version20251118124241 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Insert the creator of activity into the activity_user table';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE activity_user ADD COLUMN by_migration BOOL DEFAULT FALSE');
        $this->addSql("COMMENT ON COLUMN activity_user.by_migration IS 'For backup purpose - can be safely deleted after a while. See migration \\Chill\\Migrations\\Activity\\Version20251118124241'");

        $this->addSql('INSERT INTO activity_user (activity_id, user_id, by_migration)
            SELECT id, user_id, true FROM activity
            ON CONFLICT DO NOTHING');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE activity_user DROP COLUMN by_migration');
    }
}
