<?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 Services\Import;

use Chill\MainBundle\Repository\CountryRepository;
use Chill\MainBundle\Repository\PostalCodeRepository;
use Chill\MainBundle\Service\Import\PostalCodeBaseImporter;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @internal
 *
 * @coversNothing
 */
final class PostalCodeBaseImporterTest extends KernelTestCase
{
    private CountryRepository $countryRepository;

    private EntityManagerInterface $entityManager;

    private PostalCodeBaseImporter $importer;

    private PostalCodeRepository $postalCodeRepository;

    protected function setUp(): void
    {
        parent::setUp();

        self::bootKernel();

        $this->entityManager = self::getContainer()->get(EntityManagerInterface::class);
        $this->importer = self::getContainer()->get(PostalCodeBaseImporter::class);
        $this->postalCodeRepository = self::getContainer()->get(PostalCodeRepository::class);
        $this->countryRepository = self::getContainer()->get(CountryRepository::class);
    }

    public function testImportPostalCode(): void
    {
        $this->importer->importCode(
            'BE',
            'tested with pattern '.($uniqid = uniqid()),
            '12345',
            $refPostalCodeId = 'test'.uniqid(),
            'test',
            50.0,
            5.0,
            4326
        );

        $this->importer->finalize();

        $postalCodes = $this->postalCodeRepository->findByPattern(
            'with pattern '.$uniqid,
            $this->countryRepository->findOneBy(['countryCode' => 'BE'])
        );

        $this->assertCount(1, $postalCodes);
        $this->assertStringStartsWith('tested with pattern', $postalCodes[0]->getName());

        $previousId = $postalCodes[0]->getId();

        $this->entityManager->clear();

        $this->importer->importCode(
            'BE',
            'tested with adapted pattern '.($uniqid = uniqid()),
            '12345',
            $refPostalCodeId,
            'test',
            50.0,
            5.0,
            4326
        );

        $this->importer->finalize();

        $postalCodes = $this->postalCodeRepository->findByPattern(
            'with pattern '.$uniqid,
            $this->countryRepository->findOneBy(['countryCode' => 'BE'])
        );

        $this->assertCount(1, $postalCodes);
        $this->assertStringStartsWith('tested with adapted pattern', $postalCodes[0]->getName());
        $this->assertEquals($previousId, $postalCodes[0]->getId());
    }
}
