<?php

namespace App\Mapper;

use App\ApiResource\ContactApi;
use App\ApiResource\ContactPartnerProductApi;
use App\ApiResource\PartnerProductApi;
use App\ApiResource\ProductApi;
use App\Entity\ContactPartnerProduct;
use App\Entity\Product;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

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

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

        $dto = new ContactPartnerProductApi();
        $dto->id = $entity->getId();

        return $dto;
    }

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

        $dto->contactIri = $this->microMapper->map($entity->getContact(), ContactApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);

        $dto->partnerProductIri = $this->microMapper->map($entity->getPartnerProduct(), PartnerProductApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);

        $dto->partnerProduct = null;
        if ($entity->getPartnerProduct() !== null) {
            $dto->partnerProduct = $this->microMapper->map($entity->getPartnerProduct(), PartnerProductApi::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
        }

        $dto->product = null;
        if ($entity->getPartnerProduct() !== null && $entity->getPartnerProduct()->getProduct() !== null) {
            $dto->product = $this->microMapper->map($entity->getPartnerProduct()->getProduct(), ProductApi::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
        }

        $dto->createdAt = $entity->getCreatedAt();

        return $dto;
    }
}
