<?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\ModuleRepository;
use Gls\GlsPoland\PrestaShop\Payment\CashOnDeliveryModuleNamesProviderInterface;

final class PaymentOptionsAssembler implements CarrierAssemblerInterface
{
    private $moduleRepository;
    private $codModuleNamesProvider;

    /**
     * @var int[]
     */
    private $codModuleIds;

    public function __construct(ModuleRepository $moduleRepository, CashOnDeliveryModuleNamesProviderInterface $codModuleNamesProvider)
    {
        $this->moduleRepository = $moduleRepository;
        $this->codModuleNamesProvider = $codModuleNamesProvider;
    }

    public function assemble(DTO\Carrier $carrier, CreateCarrierCommandInterface $command): void
    {
        $moduleIds = $this->getCodModuleIds();

        if ($command->isCashOnDelivery()) {
            if ([] === $moduleIds) {
                $carrier->getCarrier()->active = false;
            }

            $carrier->setAllowedPaymentModulesIds($moduleIds);
        } else {
            $carrier->setDisallowedPaymentModulesIds($moduleIds);
        }
    }

    /**
     * @return int[]
     */
    private function getCodModuleIds(): array
    {
        if (isset($this->codModuleIds)) {
            return $this->codModuleIds;
        }

        $this->codModuleIds = [];
        foreach ($this->codModuleNamesProvider->getModuleNames() as $moduleName) {
            if (null !== $moduleId = $this->moduleRepository->getIdByName($moduleName)) {
                $this->codModuleIds[] = $moduleId;
            }
        }

        return $this->codModuleIds;
    }
}
