<?php

namespace App\Mapper;

use App\ApiResource\ProductApi;
use App\Entity\Product;
use App\Entity\User;
use App\Repository\ProductRepository;
use Symfony\Bundle\SecurityBundle\Security;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

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

    }

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

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

        if (!$entity) {
            throw new \Exception('Partner 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);

        if ($entity->getNavisionId() === null) {
            $entity->setName($dto->name);
            $entity->setDescription($dto->description);
            $entity->setBlocked($dto->blocked);
            $entity->setInventory($dto->inventory);
            $entity->setBaseUnit($dto->baseUnit);
            $entity->setBuyUnit($dto->buyUnit);
            $entity->setSellUnit($dto->sellUnit);
            $entity->setTrackingCode($dto->trackingCode);
            $entity->setProductGroup($dto->productGroup);
            $entity->setProductBookingGroup($dto->productBookingGroup);
            $entity->setVatProductBookingGroup($dto->vatProductBookingGroup);
            $entity->setCustomsPosition($dto->customsPosition);
        }

        $entity->setImage($dto->image);

        return $entity;
    }
}
