<?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\Shipment\Order;

use InPost\International\Common\DTO\Reference;
use InPost\International\Configuration\Enum\ShipmentReference;
use InPost\International\Configuration\Repository\ShippingConfigurationRepositoryInterface;
use InPost\International\Entity\PickupAddress;
use InPost\International\PickupAddress\PickupAddressRepositoryInterface;
use InPost\International\Shipment\Message\CreateShipmentCommand;

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

final class ShippingDetailsBuilder implements CreateShipmentCommandBuilderInterface
{
    /**
     * @var ShippingConfigurationRepositoryInterface
     */
    private $configurationRepository;

    /**
     * @var PickupAddressRepositoryInterface
     */
    private $pickupAddressRepository;

    /**
     * @var array{address?: PickupAddress}
     */
    private $cache = [];

    public function __construct(ShippingConfigurationRepositoryInterface $configurationRepository, PickupAddressRepositoryInterface $pickupAddressRepository)
    {
        $this->configurationRepository = $configurationRepository;
        $this->pickupAddressRepository = $pickupAddressRepository;
    }

    public function buildCommand(CreateShipmentCommand $command, \Order $order): void
    {
        $command->setPickupAddress($this->getDefaultPickupAddress());

        if (null === $configuration = $this->configurationRepository->getShippingConfiguration()) {
            return;
        }

        $command->setShippingMethod($configuration->getDefaultShippingMethod());

        if ($reference = $this->getOrderReference($order, $configuration->getDefaultShipmentReference())) {
            $command->addReference($reference);
        }
    }

    private function getDefaultPickupAddress(): ?PickupAddress
    {
        if (array_key_exists('address', $this->cache)) {
            return $this->cache['address'];
        }

        return $this->cache['address'] = $this->pickupAddressRepository->getDefault();
    }

    private function getOrderReference(\Order $order, ?ShipmentReference $type): ?Reference
    {
        switch ($type) {
            case ShipmentReference::OrderNumber():
                return new Reference('order', $order->reference);
            case ShipmentReference::OrderIdentifier():
                return new Reference('order', (string) $order->id);
            default:
                return null;
        }
    }
}
