<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Consignment\Builder;

use Gls\GlsPoland\AdePlus\Common\Services;
use Gls\GlsPoland\AdePlus\Consignment\Consignment;
use Gls\GlsPoland\AdePlus\Consignment\PPEOptions;

final class ShopReturnConsignmentBuilder extends AbstractConsignmentBuilder
{
    public function build(): Consignment
    {
        $ppeOptions = $this->buildOptions();

        return parent::build()->withReturnServiceOptions($ppeOptions);
    }

    protected function buildServices(): Services
    {
        return (new Services())->withShopReturn(true);
    }

    private function buildOptions(): PPEOptions
    {
        $options = new PPEOptions();

        if ($parcel = $this->parcels[0] ?? null) {
            $options = $options
                ->withReferences($parcel->getReference())
                ->withWeightKg($parcel->getWeightKg());
        }

        if (null !== $this->senderDetails) {
            $options = $options
                ->withSenderName1($this->senderDetails->getName1())
                ->withSenderName2($this->senderDetails->getName2())
                ->withSenderName3($this->senderDetails->getName3())
                ->withSenderCountryIsoCode($this->senderDetails->getCountryIsoCode())
                ->withSenderZipCode($this->senderDetails->getZipCode())
                ->withSenderCity($this->senderDetails->getCity())
                ->withSenderStreet($this->senderDetails->getStreet())
                ->withSenderContactInfo($this->senderDetails->getEmail())
                ->withSenderPhone($this->senderDetails->getPhone());
        }

        if (null !== $this->recipientDetails) {
            $options = $options
                ->withRecipientName1($this->recipientDetails->getName1())
                ->withRecipientName2($this->recipientDetails->getName2())
                ->withRecipientName3($this->recipientDetails->getName3())
                ->withRecipientCountryIsoCode($this->recipientDetails->getCountryIsoCode())
                ->withRecipientZipCode($this->recipientDetails->getZipCode())
                ->withRecipientCity($this->recipientDetails->getCity())
                ->withRecipientStreet($this->recipientDetails->getStreet())
                ->withRecipientContactInfo($this->recipientDetails->getEmail())
                ->withRecipientPhone($this->recipientDetails->getPhone());
        }

        return $options;
    }
}
