<?php

namespace App\Mapper;

use App\ApiResource\UserProductApi;
use App\Entity\Product;
use App\Entity\User;
use App\Entity\UserProduct;
use App\Repository\UserProductRepository;
use Symfony\Bundle\SecurityBundle\Security;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: UserProductApi::class, to: UserProduct::class)]
class UserProductApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private UserProductRepository    $repository,
        private Security             $security,
        private MicroMapperInterface $microMapper,
    )
    {

    }

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

        if ($dto->id) {
            $entity = $this->repository->find($dto->id);
        } else {
            $user = $this->security->getUser();
            assert($user instanceof User);

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

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

        return $entity;
    }

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