<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Order;

use Gls\GlsPoland\Consignment\DTO\AddressDetails;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\AddressRepository;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\CountryRepository;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\CustomerRepository;

final class AddressDetailsFactory implements AddressDetailsFactoryInterface
{
    private $addressRepository;
    private $customerRepository;
    private $countryRepository;

    public function __construct(AddressRepository $addressRepository, CustomerRepository $customerRepository, CountryRepository $countryRepository)
    {
        $this->addressRepository = $addressRepository;
        $this->customerRepository = $customerRepository;
        $this->countryRepository = $countryRepository;
    }

    public function create(int $addressId): AddressDetails
    {
        if (null === $address = $this->addressRepository->find($addressId)) {
            return new AddressDetails();
        }

        $customer = $this->customerRepository->find((int) $address->id_customer);
        $country = $this->countryRepository->find((int) $address->id_country);

        return (new AddressDetails())
            ->setName1($address->lastname)
            ->setName2($address->firstname)
            ->setName3($address->company)
            ->setStreet($this->getStreetAddress($address))
            ->setCity($address->city)
            ->setZipCode($address->postcode)
            ->setCountryIsoCode($country->iso_code ?? null)
            ->setPhone($address->phone_mobile ?: $address->phone)
            ->setEmail($customer->email ?? null);
    }

    private function getStreetAddress(\Address $address): ?string
    {
        if ('' === $address2 = (string) $address->address2) {
            return $address->address1;
        }

        return sprintf('%s %s', $address->address1, $address2);
    }
}
