<?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\ParcelsCollection;
use Gls\GlsPoland\Consignment\DTO\Parcel;

class CourierConsignmentBuilder extends AbstractConsignmentBuilder
{
    public function build(): Consignment
    {
        $senderAddress = $this->senderDetails ? $this->senderDetails->asAdeSenderAddress() : null;
        $parcels = array_map(static function (Parcel $parcel) {
            return $parcel->asAdeParcel();
        }, $this->parcels);

        return parent::build()
            ->withSenderAddress($senderAddress)
            ->withParcels(new ParcelsCollection(...$parcels));
    }

    protected function buildServices(): Services
    {
        if (null === $this->serviceDetails) {
            return new Services();
        }

        return (new Services())
            ->withCashOnDelivery($isCod = $this->serviceDetails->isCashOnDelivery())
            ->withCashOnDeliveryAmount($isCod ? $this->serviceDetails->getCashOnDeliveryAmount() : null)
            ->withDeliveryBefore10($this->serviceDetails->isDeliveryBefore10())
            ->withDeliveryBefore12($this->serviceDetails->isDeliveryBefore12())
            ->withSaturdayDelivery($this->serviceDetails->isSaturdayDelivery())
            ->withDocumentReturn($this->serviceDetails->isDocumentReturn());
    }
}
