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

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

/**
 * Create view for PersonCurrentAddress and related indexes.
 */
final class Version20210915093624 extends AbstractMigration
{
    public function down(Schema $schema): void
    {
        $this->addSql('DROP VIEW view_chill_person_current_address');
        $this->addSql('DROP INDEX chill_custom_main_address_filtering_idx');
        $this->addSql('DROP INDEX chill_custom_person_household_members_sharing_idx');
    }

    public function getDescription(): string
    {
        return 'Create view for PersonCurrentAddress and related indexes';
    }

    public function up(Schema $schema): void
    {
        $this->addSql("CREATE VIEW view_chill_person_current_address AS
            SELECT
                cphm.person_id  AS person_id,
                cma.id AS address_id,
                CASE WHEN cphm.startdate > COALESCE(cma.validfrom, '-infinity'::date) THEN cphm.startdate ELSE cma.validfrom END AS valid_from,
                CASE WHEN COALESCE(cphm.enddate, 'infinity'::date) < COALESCE(cma.validto, 'infinity'::date) THEN cphm.enddate ELSE cma.validto END AS valid_to
            FROM chill_person_household_members AS cphm
                     LEFT JOIN chill_person_household_to_addresses AS cphta ON cphta.household_id = cphm.household_id
                     LEFT JOIN chill_main_address AS cma ON cphta.address_id = cma.id
            WHERE
                  cphm.sharedhousehold IS TRUE
            AND
                  current_date between cphm.startdate AND coalesce(enddate, 'infinity'::date)
            AND
                  current_date between cma.validfrom AND coalesce(validto, 'infinity'::date)
      ");

        $this->addSql('CREATE INDEX chill_custom_main_address_filtering_idx ON chill_main_address USING btree (id, validfrom ASC, validto DESC)');
        $this->addSql('CREATE INDEX chill_custom_person_household_members_sharing_idx ON chill_person_household_members USING btree (person_id, startdate ASC, enddate DESC, household_id) WHERE sharedhousehold IS TRUE');
    }
}
