<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Configuration\MessageHandler;

use InPost\International\Configuration\Message\UpdateOrdersConfigurationCommand;
use InPost\International\Configuration\Repository\MailsConfigurationRepositoryInterface;
use InPost\International\Configuration\Repository\OrdersConfigurationRepositoryInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class UpdateOrdersConfigurationHandler
{
    /**
     * @var OrdersConfigurationRepositoryInterface
     */
    private $ordersConfigRepository;

    /**
     * @var MailsConfigurationRepositoryInterface
     */
    private $mailsConfigRepository;

    public function __construct(OrdersConfigurationRepositoryInterface $ordersConfigRepository, MailsConfigurationRepositoryInterface $mailsConfigRepository)
    {
        $this->ordersConfigRepository = $ordersConfigRepository;
        $this->mailsConfigRepository = $mailsConfigRepository;
    }

    public function __invoke(UpdateOrdersConfigurationCommand $command): void
    {
        $this->updateOrdersConfig($command);
        $this->updateMailsConfig($command);
    }

    public function handle(UpdateOrdersConfigurationCommand $command): void
    {
        ($this)($command);
    }

    private function updateOrdersConfig(UpdateOrdersConfigurationCommand $command): void
    {
        $configuration = $this->ordersConfigRepository->getOrdersConfiguration()
            ->withLabelPrintedStatusId($command->getLabelPrintedStatusId())
            ->withShipmentDeliveredStatusId($command->getShipmentDeliveredStatusId());

        $this->ordersConfigRepository->saveOrdersConfiguration($configuration);
    }

    private function updateMailsConfig(UpdateOrdersConfigurationCommand $command): void
    {
        if (null === $modifyOrderConfirmation = $command->getModifyOrderConfirmationMail()) {
            return;
        }

        $configuration = $this->mailsConfigRepository->getMailsConfiguration()
            ->withModifyOrderConfirmation($modifyOrderConfirmation);

        $this->mailsConfigRepository->saveMailsConfiguration($configuration);
    }
}
