<?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\PickupAddress\MessageHandler;

use InPost\International\Entity\PickupAddress;
use InPost\International\PickupAddress\Exception\PickupAddressException;
use InPost\International\PickupAddress\Message\CreatePickupAddressCommand;
use InPost\International\PickupAddress\PickupAddressMapper;
use InPost\International\PickupAddress\PickupAddressRepositoryInterface;

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

final class CreatePickupAddressHandler
{
    /**
     * @var PickupAddressRepositoryInterface
     */
    private $repository;

    /**
     * @var PickupAddressMapper
     */
    private $mapper;

    public function __construct(PickupAddressRepositoryInterface $repository, PickupAddressMapper $mapper)
    {
        $this->repository = $repository;
        $this->mapper = $mapper;
    }

    public function __invoke(CreatePickupAddressCommand $command): PickupAddress
    {
        $address = $this->createPickupAddress($command);

        if (null === $defaultAddress = $this->repository->getDefault()) {
            $address->setDefault(true);
        } elseif ($command->isDefault()) {
            $defaultAddress->setDefault(false);
            $address->setDefault(true);
        }

        $this->repository->add($address);

        return $address;
    }

    public function handle(CreatePickupAddressCommand $command): PickupAddress
    {
        return ($this)($command);
    }

    private function createPickupAddress(CreatePickupAddressCommand $command): PickupAddress
    {
        if (null === $contactPerson = $command->getContactPerson()) {
            throw new PickupAddressException('Contact details are required.');
        }

        if (null === $address = $command->getAddress()) {
            throw new PickupAddressException('Address is required.');
        }

        return new PickupAddress(
            (string) $command->getName(),
            $this->mapper->mapDtoToContactPerson($contactPerson),
            $this->mapper->mapDtoToAddress($address)
        );
    }
}
