<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\ObjectModel\Repository;

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

/**
 * @extends AbstractObjectModelRepository<\TaxRulesGroup>
 */
final class TaxRulesGroupRepository extends AbstractObjectModelRepository
{
    public function __construct(Connection $connection, string $dbPrefix, HydratorInterface $hydrator = null)
    {
        parent::__construct(\TaxRulesGroup::class, $connection, $dbPrefix, $hydrator);
    }

    public function findOneByCountryIdAndTaxRate(int $countryId, float $taxRate): ?\TaxRulesGroup
    {
        if (0 >= $countryId) {
            return null;
        }

        $statement = $this
            ->createQueryBuilder('trg')
            ->innerJoin('trg', 'tax_rule', 'tr', 'tr.id_tax_rules_group = trg.id_tax_rules_group')
            ->innerJoin('tr', 'tax', 't', 't.id_tax = tr.id_tax')
            ->andWhere('tr.id_country = :countryId')
            ->andWhere('t.rate = :taxRate')
            ->andWhere('trg.deleted = 0')
            ->andWhere('tr.id_state = 0')
            ->setParameter('countryId', $countryId)
            ->setParameter('taxRate', $taxRate)
            ->setMaxResults(1)
            ->execute();

        $data = $this->fetchAllAssociative($statement);

        return $this->hydrate($data);
    }
}
