<?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 Version20240926100337 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add foreign key gender property to person and transfer values';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE chill_person_person ADD gender_id INT DEFAULT NULL');
        $this->addSql('ALTER TABLE chill_person_person ADD CONSTRAINT FK_BF210A14708A0E0 FOREIGN KEY (gender_id) REFERENCES chill_main_gender (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('CREATE INDEX IDX_BF210A14708A0E0 ON chill_person_person (gender_id)');

        // transfer gender values to point to corresponding gender entity within new column
        $this->addSql("
            UPDATE chill_person_person AS p
            SET gender_id = g.id
            FROM chill_main_gender AS g
            WHERE g.genderTranslation = p.gender AND p.gender IN ('man', 'woman', 'unknown')
              OR (g.genderTranslation = 'neutral' AND p.gender = 'both')
        ");

        // delete old gender column
        $this->addSql('ALTER TABLE chill_person_person DROP gender');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE chill_person_person ADD gender VARCHAR(9) DEFAULT NULL');
        $this->addSql('ALTER TABLE chill_person_person DROP gender_id');
    }
}
