<?php

namespace App\Mapper;

use App\ApiResource\ProductApi;
use App\Entity\Product;
use App\Repository\ProductRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;

#[AsMapper(from: ProductApi::class, to: Product::class)]
class ProductApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private ProductRepository $repository
    )
    {

    }

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

        $entity = $dto->id ? $this->repository->find($dto->id) : new Product();
        if (!$entity) {
            throw new \Exception('Product not found');
        }

        return $entity;
    }

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

        $entity->setName($dto->name);
        $entity->setDescription($dto->description);
        $entity->setImage($dto->image);

        return $entity;
    }
}
