<?php

declare(strict_types=1);

namespace Gls\GlsPoland\MessageHandler\Pickup;

use Gls\GlsPoland\AdePlus\Pickup\ClientInterface;
use Gls\GlsPoland\Configuration\Orders;
use Gls\GlsPoland\Consignment\Exception\ConsignmentNotFoundException;
use Gls\GlsPoland\Consignment\Exception\NoPickupForConsignmentException;
use Gls\GlsPoland\Download\Base64EncodedFile;
use Gls\GlsPoland\Download\StreamableFileInterface;
use Gls\GlsPoland\Message\PrintPickupReceiptCommand;
use Gls\GlsPoland\Repository\ConsignmentRepository;

final class PrintPickupReceiptHandler implements PrintPickupReceiptHandlerInterface
{
    private $repository;
    private $configuration;
    private $client;

    public function __construct(ConsignmentRepository $repository, Orders\ConfigurationInterface $configuration, ClientInterface $client)
    {
        $this->repository = $repository;
        $this->configuration = $configuration;
        $this->client = $client;
    }

    public function handle(PrintPickupReceiptCommand $command): StreamableFileInterface
    {
        if (null === $consignment = $this->repository->find($command->getConsignmentId())) {
            throw ConsignmentNotFoundException::create($command->getConsignmentId());
        }

        if (null === $pickupId = $consignment->getPickupId()) {
            throw NoPickupForConsignmentException::create($consignment->getId());
        }

        $printMode = $this->configuration->getPickupReceiptPrintMode();
        $receipt = $this->client->getReceipt($pickupId, $printMode);

        return new Base64EncodedFile($receipt, $printMode);
    }
}
