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

final class Version20220413154743 extends AbstractMigration
{
    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE chill_main_notification DROP adressesEmails');
        $this->addSql('ALTER TABLE chill_main_notification DROP accessKey');
    }

    public function getDescription(): string
    {
        return 'add access keys and emails dest to notifications';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE chill_main_notification ADD addressesEmails JSON NOT NULL DEFAULT \'[]\';');
        $this->addSql('ALTER TABLE chill_main_notification ADD accessKey TEXT DEFAULT NULL');
        $this->addSql('WITH randoms AS (select
                n.id,
                string_agg(substr(characters, (random() * length(characters) + 0.5)::integer, 1), \'\') as random_word
             from (values(\'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\')) as symbols(characters)
                -- length of word
                join generate_series(1, 16) on 1 = 1
            JOIN chill_main_notification n ON true
            GROUP BY n.id)
        UPDATE chill_main_notification SET accessKey = randoms.random_word FROM randoms WHERE chill_main_notification.id = randoms.id');
        $this->addSql('ALTER TABLE chill_main_notification ALTER accessKey DROP DEFAULT');
        $this->addSql('ALTER TABLE chill_main_notification ALTER accessKey SET NOT NULL');
    }
}
