<?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 Version20211125142017 extends AbstractMigration
{
    public function down(Schema $schema): void
    {
        $this->addSql('DROP TRIGGER canonicalize_postal_code_on_insert ON chill_main_postal_code');
        $this->addSql('DROP TRIGGER canonicalize_postal_code_on_update ON chill_main_postal_code');
        $this->addSql('DROP FUNCTION canonicalize_postal_code()');
        $this->addSql('ALTER TABLE chill_main_postal_code DROP COLUMN canonical');
    }

    public function getDescription(): string
    {
        return 'Add a column "canonicalized" on postal code';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE chill_main_postal_code ADD canonical TEXT DEFAULT \'\' NOT NULL');

        $this->addSql('UPDATE chill_main_postal_code
        SET canonical =
                TRIM(
                    UNACCENT(
                        LOWER(
                            code ||
                            \' \' ||
                            label
                        )
                    )

                )');

        $this->addSql('CREATE OR REPLACE FUNCTION public.canonicalize_postal_code() RETURNS TRIGGER
            LANGUAGE plpgsql
        AS
        $$
        BEGIN
            NEW.canonical =
                TRIM(
                    UNACCENT(
                        LOWER(
                            NEW.code ||
                            \' \' ||
                            NEW.label
                        )
                    )

                )
            ;

            return NEW;
        END
        $$');

        $this->addSql('CREATE TRIGGER canonicalize_postal_code_on_insert
            BEFORE INSERT
            ON chill_main_postal_code
            FOR EACH ROW
                EXECUTE procedure canonicalize_postal_code()');

        $this->addSql('CREATE TRIGGER canonicalize_postal_code_on_update
            BEFORE UPDATE
            ON chill_main_postal_code
            FOR EACH ROW
                EXECUTE procedure canonicalize_postal_code()');

        $this->addSql('CREATE INDEX chill_internal_postal_code_canonicalized ON chill_main_postal_code USING GIST (canonical gist_trgm_ops) WHERE origin = 0');
    }
}
