<?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;
use libphonenumber\PhoneNumberUtil;

final class Version20220215135509 extends AbstractMigration
{
    public function down(Schema $schema): void
    {
        throw new \Exception('You should not do that.');
    }

    public function getDescription(): string
    {
        return 'Update phone numbers for person';
    }

    public function up(Schema $schema): void
    {
        $carrierCode = getenv('DEFAULT_CARRIER_CODE'); // Directly from the .env

        if (!$carrierCode) {
            throw new \RuntimeException('Environment variable DEFAULT_CARRIER_CODE is not set.');
        }

        $this->addSql('ALTER TABLE chill_person_person ALTER phonenumber TYPE TEXT');
        $this->addSql('ALTER TABLE chill_person_person ALTER phonenumber DROP DEFAULT');
        $this->addSql('ALTER TABLE chill_person_person ALTER phonenumber DROP NOT NULL');
        $this->addSql('COMMENT ON COLUMN chill_person_person.phonenumber IS NULL');

        $this->addSql('ALTER TABLE chill_person_person ALTER mobilenumber TYPE TEXT');
        $this->addSql('ALTER TABLE chill_person_person ALTER mobilenumber DROP DEFAULT');
        $this->addSql('ALTER TABLE chill_person_person ALTER mobilenumber DROP NOT NULL');
        $this->addSql('COMMENT ON COLUMN chill_person_person.mobilenumber IS NULL');

        $this->addSql(
            'UPDATE chill_person_person SET '.
            $this->buildMigrationPhonenumberClause($carrierCode, 'phonenumber').
            ', '.
            $this->buildMigrationPhoneNumberClause($carrierCode, 'mobilenumber')
        );

        $this->addSql('ALTER TABLE chill_person_phone ALTER phonenumber TYPE TEXT');
        $this->addSql('ALTER TABLE chill_person_phone ALTER phonenumber DROP DEFAULT');
        $this->addSql('ALTER TABLE chill_person_phone ALTER phonenumber DROP NOT NULL');
        $this->addSql('COMMENT ON COLUMN chill_person_phone.phonenumber IS NULL');

        $this->addSql(
            'UPDATE chill_person_phone SET '.
            $this->buildMigrationPhoneNumberClause($carrierCode, 'phonenumber')
        );
    }

    private function buildMigrationPhoneNumberClause(string $defaultCarriercode, string $field): string
    {
        $util = PhoneNumberUtil::getInstance();

        $countryCode = $util->getCountryCodeForRegion($defaultCarriercode);

        return sprintf('%s=CASE
                WHEN %s = \'\' THEN NULL
                WHEN LEFT(%s, 1) = \'0\'
                    THEN \'+%s\' || replace(replace(substr(%s, 2), \'(0)\', \'\'), \' \', \'\')
                ELSE replace(replace(%s, \'(0)\', \'\'),\' \', \'\')
            END', $field, $field, $field, $countryCode, $field, $field);
    }
}
