<?php

namespace App\Mapper;

use App\ApiResource\ProductApi;
use App\ApiResource\UserApi;
use App\Entity\Product;
use App\Service\FileUrlService;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: Product::class, to: ProductApi::class)]
class ProductEntityToApiMapper implements MapperInterface
{
    public function __construct(
        private MicroMapperInterface $microMapper,
        private FileUrlService $fileUrlService
    ) {
    }

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

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

        return $dto;
    }

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

        $dto->name = $entity->getName();
        $dto->description = $entity->getDescription();
        $dto->blocked = $entity->isBlocked();
        $dto->inventory = $entity->getInventory();
        $dto->baseUnit = $entity->getBaseUnit();
        $dto->buyUnit = $entity->getBuyUnit();
        $dto->sellUnit = $entity->getSellUnit();
        $dto->trackingCode = $entity->getTrackingCode();
        $dto->productGroup = $entity->getProductGroup();
        $dto->vatProductBookingGroup = $entity->getVatProductBookingGroup();
        $dto->productBookingGroup = $entity->getProductBookingGroup();
        $dto->customsPosition = $entity->getCustomsPosition();
        $dto->image = $entity->getImage();
        $dto->imageUrl = $this->fileUrlService->getFileUrl($entity->getImage());
        $dto->createdBy = $this->microMapper->map($entity->getCreatedBy(), UserApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);
        return $dto;
    }
}
