<?php

namespace App\Mapper;

use App\ApiResource\ProductApi;
use App\ApiResource\UserApi;
use App\ApiResource\UserProductApi;
use App\Entity\UserProduct;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: UserProduct::class, to: UserProductApi::class)]
class UserProductEntityToApiMapper implements MapperInterface
{
    public function __construct(
        private MicroMapperInterface $microMapper
    )
    {
    }

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

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

        return $dto;
    }

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

        $dto->user = $this->microMapper->map($entity->getUser(), UserApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);

        $dto->product = $this->microMapper->map($entity->getProduct(), ProductApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);
        $dto->productIri = $this->microMapper->map($entity->getProduct(), ProductApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);

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

        return $dto;
    }
}
