<?php

namespace App\Mapper;

use App\ApiResource\PartnerApi;
use App\ApiResource\PostingApi;
use App\Entity\Contact;
use App\Entity\Partner;
use App\Entity\User;
use App\Entity\Posting;
use App\Repository\PartnerRepository;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: PartnerApi::class, to: Partner::class)]
class PartnerApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private PartnerRepository $repository,
        private Security             $security,
    )
    {

    }

    public function load(object $from, string $toClass, array $context): object
    {
        $dto = $from;
        assert($dto instanceof PartnerApi);

        if ($dto->id) {
            $entity = $this->repository->find($dto->id);
            assert($entity instanceof Partner);

        } else {
            $user = $this->security->getUser();
            assert($user instanceof User);
            $entity = new Partner($user);
        }

        if (!$entity) {
            throw new \Exception('Partner not found');
        }

        return $entity;
    }

    public function populate(object $from, object $to, array $context): object
    {
        $dto = $from;
        assert($dto instanceof PartnerApi);
        $entity = $to;
        assert($entity instanceof Partner);

        if ($entity->getNavisionId() === null) {
            $entity->setName($dto->name);
            $entity->setNameAddition($dto->nameAddition);
            $entity->setType($dto->partnerType);
            $entity->setStreet($dto->street);
            $entity->setStreetNo($dto->streetNo);
            $entity->setZip($dto->zip);
            $entity->setCity($dto->city);
            $entity->setCountry($dto->country);
            $entity->setAddressAddition($dto->addressAddition);
            $entity->setPhone($dto->phone);
            $entity->setLanguage($dto->language);
            $entity->setCurrency($dto->currency);
            $entity->setPaymentCondition($dto->paymentCondition);
            $entity->setDeliveryCondition($dto->deliveryCondition);
            $entity->setBusinessGroup($dto->businessGroup);
            $entity->setVatBusinessGroup($dto->vatBusinessGroup);
            $entity->setCreditLimit($dto->creditLimit);
            $entity->setRoutePoint($dto->routePoint);
        }
        $entity->setLogo($dto->logo);
        $entity->setWebsite($dto->website);
        $entity->setDescription($dto->description);

        return $entity;
    }
}
