<?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 Version20221114105345 extends AbstractMigration
{
    public function down(Schema $schema): void
    {
        $this->addSql('DROP MATERIALIZED VIEW view_chill_main_address_geographical_unit');
    }

    public function getDescription(): string
    {
        return 'Create materialized view to store GeographicalUnitAddress';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('CREATE MATERIALIZED VIEW view_chill_main_address_geographical_unit (address_id, geographical_unit_id) AS
            SELECT
                address.id AS address_id,
                geographical_unit.id AS geographical_unit_id
            FROM chill_main_address AS address
                 JOIN chill_main_geographical_unit AS geographical_unit ON ST_CONTAINS(geographical_unit.geom, address.point)
        ');

        $this->addSql('CREATE INDEX IDX_BD42692CF5B7AF75 ON view_chill_main_address_geographical_unit (address_id)');
        $this->addSql('CREATE INDEX IDX_BD42692CDAA4DAB8 ON view_chill_main_address_geographical_unit (geographical_unit_id)');
    }
}
