<?php

namespace App\Mapper;

use App\ApiResource\PartnerProductApi;
use App\Entity\Partner;
use App\Entity\PartnerProduct;
use App\Entity\Product;
use App\Repository\PartnerProductRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: PartnerProductApi::class, to: PartnerProduct::class)]
class PartnerProductApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private PartnerProductRepository    $repository,
        private MicroMapperInterface $microMapper,
    )
    {

    }

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

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

            if ($dto->productIri === null) {
                throw new \Exception('Product missing');
            }
            $product = $this->microMapper->map($dto->productIri, Product::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
            assert($partner instanceof Partner);
            assert($product instanceof Product);
            $entity = new PartnerProduct($partner, $product);
        }

        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 PartnerProductApi);
        $entity = $to;
        assert($entity instanceof PartnerProduct);
        return $entity;
    }
}
