<?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\Api\Shipment\Model\Phone;
use InPost\International\Api\Shipment\Model\Sender;
use InPost\International\Api\Shipment\Model\Service\Currency;
use InPost\International\Api\Shipment\Model\Service\Insurance;
use InPost\International\Common\DTO\ContactDetails;
use InPost\International\Configuration\Message\UpdateShippingConfigurationCommand;
use InPost\International\Configuration\Repository\ShippingConfigurationRepositoryInterface;
use InPost\International\Configuration\ShippingConfiguration;

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

final class UpdateShippingConfigurationHandler
{
    /**
     * @var ShippingConfigurationRepositoryInterface
     */
    private $repository;

    public function __construct(ShippingConfigurationRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }

    public function __invoke(UpdateShippingConfigurationCommand $command): void
    {
        $configuration = $this->createShippingConfiguration($command);
        $this->repository->saveShippingConfiguration($configuration);
    }

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

    private function createShippingConfiguration(UpdateShippingConfigurationCommand $command): ShippingConfiguration
    {
        $sender = $this->createSender($command->getSender());
        $insurance = $this->getInsurance($command->getDefaultInsurance());

        return new ShippingConfiguration(
            $sender,
            $command->getDefaultShippingMethod(),
            $command->getDefaultShipmentReference(),
            $command->getDefaultParcelComment(),
            $insurance
        );
    }

    private function createSender(ContactDetails $data): Sender
    {
        $phone = new Phone(
            (string) $data->getPhone()->getPrefix(),
            (string) $data->getPhone()->getNumber()
        );

        return new Sender(
            (string) $data->getFirstName(),
            (string) $data->getLastName(),
            (string) $data->getEmail(),
            $phone,
            $data->getCompanyName()
        );
    }

    private function getInsurance(?float $amount): ?Insurance
    {
        if (null === $amount) {
            return null;
        }

        return new Insurance($amount, Currency::getDefault());
    }
}
