<?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 Version20211125142016 extends AbstractMigration
{
    public function down(Schema $schema): void
    {
        $this->addSql('DROP TRIGGER canonicalize_address_reference_on_insert ON chill_main_address_reference');
        $this->addSql('DROP TRIGGER canonicalize_address_reference_on_update ON chill_main_address_reference');
        $this->addSql('DROP FUNCTION canonicalize_address_reference()');
        $this->addSql('ALTER TABLE chill_main_address_reference DROP COLUMN addressCanonical');
    }

    public function getDescription(): string
    {
        return 'Add a column "canonicalized" on chill_main_address_reference and add trigger and indexed on it';
    }

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

        $this->addSql('UPDATE chill_main_address_reference
        SET addresscanonical =
                TRIM(
                    UNACCENT(
                        LOWER(
                            street ||
                            \' \' ||
                            streetnumber
                        )
                    )

                )');

        $this->addSql('CREATE OR REPLACE FUNCTION public.canonicalize_address_reference() RETURNS TRIGGER
            LANGUAGE plpgsql
        AS
        $$
        BEGIN
            NEW.addresscanonical =
                TRIM(
                    UNACCENT(
                        LOWER(
                            NEW.street ||
                            \' \' ||
                            NEW.streetnumber
                        )
                    )

                )
            ;

            return NEW;
        END
        $$');

        $this->addSql('CREATE TRIGGER canonicalize_address_reference_on_insert
            BEFORE INSERT
            ON chill_main_address_reference
            FOR EACH ROW
                EXECUTE procedure canonicalize_address_reference()');

        $this->addSql('CREATE TRIGGER canonicalize_address_reference_on_update
            BEFORE UPDATE
            ON chill_main_address_reference
            FOR EACH ROW
                EXECUTE procedure canonicalize_address_reference()');

        $this->addSql('CREATE INDEX chill_internal_address_reference_canonicalized ON chill_main_address_reference USING GIST (postcode_id, addressCanonical gist_trgm_ops)');
    }
}
