<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\MessageHandler\Carrier\Assembler;

use Gls\GlsPoland\PrestaShop\DTO;
use Gls\GlsPoland\PrestaShop\Message\CreateCarrierCommandInterface;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\CountryRepository;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\TaxRulesGroupRepository;

final class TaxRulesGroupAssembler implements CarrierAssemblerInterface
{
    private $countryRepository;
    private $taxRulesGroupRepository;

    private $taxRulesGroup;

    public function __construct(CountryRepository $countryRepository, TaxRulesGroupRepository $taxRulesGroupRepository)
    {
        $this->countryRepository = $countryRepository;
        $this->taxRulesGroupRepository = $taxRulesGroupRepository;
    }

    public function assemble(DTO\Carrier $carrier, CreateCarrierCommandInterface $command): void
    {
        if (null === $taxRulesGroup = $this->getTaxRulesGroup()) {
            return;
        }

        $carrier->setTaxRulesGroup($taxRulesGroup);
    }

    private function getTaxRulesGroup(): ?\TaxRulesGroup
    {
        if (!isset($this->taxRulesGroup)) {
            $country = $this->countryRepository->findOneByIsoCode('PL');

            if (
                null === $country ||
                null === $taxRulesGroup = $this->taxRulesGroupRepository->findOneByCountryIdAndTaxRate((int) $country->id, 23.)
            ) {
                $this->taxRulesGroup = false;
            } else {
                $this->taxRulesGroup = $taxRulesGroup;
            }
        }

        return $this->taxRulesGroup ?: null;
    }
}
