<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\ObjectModel\Repository;

use Doctrine\DBAL\Connection;
use Gls\GlsPoland\PrestaShop\ObjectModel\HydratorInterface;

/**
 * @extends AbstractMultiLangObjectModelRepository<\Country>
 */
final class CountryRepository extends AbstractMultiLangObjectModelRepository
{
    private $countriesByIsoCode = [];

    public function __construct(Connection $connection, string $dbPrefix, HydratorInterface $hydrator = null)
    {
        parent::__construct(\Country::class, $connection, $dbPrefix, $hydrator);
    }

    public function findOneByIsoCode(string $isoCode): ?\Country
    {
        if (array_key_exists($isoCode, $this->countriesByIsoCode)) {
            return $this->countriesByIsoCode[$isoCode];
        }

        $statement = $this
            ->createLangQueryBuilder('c')
            ->andWhere('c.iso_code = :isoCode')
            ->addOrderBy('c.active', 'DESC')
            ->setParameter('isoCode', $isoCode)
            ->execute();

        $data = $this->fetchAllAssociative($statement);
        $collection = $this->hydrateCollection($data);
        $country = current($collection) ?: null;

        return $this->countriesByIsoCode[$isoCode] = $country;
    }
}
