<?php

namespace App\Mapper;

use App\ApiResource\DocumentApi;
use App\Entity\Document;
use App\Entity\Partner;
use App\Entity\Product;
use App\Entity\User;
use App\Repository\DocumentRepository;
use Symfony\Bundle\SecurityBundle\Security;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: DocumentApi::class, to: Document::class)]
class DocumentApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private DocumentRepository   $repository,
        private Security             $security,
        private MicroMapperInterface $microMapper,
    )
    {

    }

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

        if ($dto->id) {
            $entity = $this->repository->find($dto->id);
        } else {
            $user = $this->security->getUser();
            assert($user instanceof User);
            if ($dto->documentObject === null) {
                throw new \Exception('Document object missing');
            }
            $entity = new Document($user, $dto->documentObject);
        }

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

        return $entity;
    }

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

        $entity->setName($dto->name);
        $entity->setDescription($dto->description);
        if ($dto->partnerIri !== null) {
            $entity->setPartner(
                $this->microMapper->map($dto->partnerIri, Partner::class, [
                    MicroMapperInterface::MAX_DEPTH => 1,
                ])
            );
        } else {
            $entity->setPartner(null);
        }
        if ($dto->productIri !== null) {
            $entity->setProduct(
                $this->microMapper->map($dto->productIri, Product::class, [
                    MicroMapperInterface::MAX_DEPTH => 1,
                ])
            );
        } else {
            $entity->setProduct(null);
        }
        if ($dto->documentObject?->getId() !== $entity->getDocumentObject()?->getId()) {
            $entity->setDocumentObject($dto->documentObject);
        }
        return $entity;
    }
}
