<?php

namespace App\Mapper;

use App\ApiResource\ContactPartnerProductApi;
use App\ApiResource\PartnerProductApi;
use App\Entity\Contact;
use App\Entity\ContactPartnerProduct;
use App\Entity\Partner;
use App\Entity\PartnerProduct;
use App\Entity\Product;
use App\Repository\ContactPartnerProductRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: ContactPartnerProductApi::class, to: ContactPartnerProduct::class)]
class ContactPartnerProductApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private ContactPartnerProductRepository $repository,
        private MicroMapperInterface $microMapper,
    )
    {

    }

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

        if ($dto->id) {
            $entity = $this->repository->find($dto->id);
        } else {
            if ($dto->contactIri === null) {
                throw new \Exception('Contact missing');
            }
            $contact = $this->microMapper->map($dto->contactIri, Contact::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);

            if ($dto->partnerProductIri === null) {
                throw new \Exception('PartnerProduct missing');
            }
            $partnerProduct = $this->microMapper->map($dto->partnerProductIri, PartnerProduct::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);

            if ($contact->getPartner() !== $partnerProduct->getPartner()) {
                throw new \Exception('Contact Partner and ProductPartner Partner do not match!');
            }

            assert($contact instanceof Contact);
            assert($partnerProduct instanceof PartnerProduct);
            $entity = new ContactPartnerProduct($contact, $partnerProduct);
        }

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

        return $entity;
    }

    public function populate(object $from, object $to, array $context): object
    {
        $dto = $from;
        assert($dto instanceof ContactPartnerProductApi);
        $entity = $to;
        assert($entity instanceof ContactPartnerProduct);
        return $entity;
    }
}
