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

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

/**
 * Add metadata on users.
 */
final class Version20210903144853 extends AbstractMigration
{
    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE users DROP CONSTRAINT FK_1483A5E964B65C5B');
        $this->addSql('DROP SEQUENCE chill_main_user_job_id_seq CASCADE');
        $this->addSql('DROP TABLE chill_main_user_job');
        $this->addSql('ALTER TABLE users DROP CONSTRAINT FK_1483A5E92C2125C1');
        $this->addSql('ALTER TABLE users DROP CONSTRAINT FK_1483A5E9115E73F3');
        $this->addSql('ALTER TABLE users DROP label');
        $this->addSql('ALTER TABLE users DROP mainCenter_id');
        $this->addSql('ALTER TABLE users DROP mainScope_id');
        $this->addSql('ALTER TABLE users DROP userJob_id');
        $this->addSql('ALTER TABLE users ALTER usernameCanonical DROP NOT NULL');
    }

    public function getDescription(): string
    {
        return 'Add metadata on users';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('CREATE SEQUENCE chill_main_user_job_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
        $this->addSql('CREATE TABLE chill_main_user_job (id INT NOT NULL, label JSON NOT NULL, active BOOLEAN NOT NULL, PRIMARY KEY(id))');
        $this->addSql('ALTER TABLE users ADD label VARCHAR(200) NULL DEFAULT NULL');
        $this->addSql('UPDATE users SET label=username');
        $this->addSql('ALTER TABLE users ALTER label DROP DEFAULT');
        $this->addSql('ALTER TABLE users ALTER label SET NOT NULL');
        $this->addSql('ALTER TABLE users ADD mainCenter_id INT DEFAULT NULL');
        $this->addSql('ALTER TABLE users ADD mainScope_id INT DEFAULT NULL');
        $this->addSql('ALTER TABLE users ADD userJob_id INT DEFAULT NULL');
        $this->addSql('ALTER TABLE users ADD CONSTRAINT FK_1483A5E92C2125C1 FOREIGN KEY (mainCenter_id) REFERENCES centers (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('ALTER TABLE users ADD CONSTRAINT FK_1483A5E9115E73F3 FOREIGN KEY (mainScope_id) REFERENCES scopes (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('ALTER TABLE users ADD CONSTRAINT FK_1483A5E964B65C5B FOREIGN KEY (userJob_id) REFERENCES chill_main_user_job (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('CREATE INDEX IDX_1483A5E92C2125C1 ON users (mainCenter_id)');
        $this->addSql('CREATE INDEX IDX_1483A5E9115E73F3 ON users (mainScope_id)');
        $this->addSql('CREATE INDEX IDX_1483A5E964B65C5B ON users (userJob_id)');
    }
}
