<?php

namespace App\Mapper;

use App\ApiResource\CommentApi;
use App\ApiResource\DocumentApi;
use App\ApiResource\PartnerApi;
use App\ApiResource\ProductApi;
use App\ApiResource\UserApi;
use App\ApiResource\PostingApi;
use App\Entity\Comment;
use App\Entity\Document;
use App\Service\FileUrlService;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: Document::class, to: DocumentApi::class)]
class DocumentEntityToApiMapper 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 Document);

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

        return $dto;
    }

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

        $dto->name = $entity->getName();
        $dto->description = $entity->getDescription();

        $dto->partnerIri = null;
        if ($entity->getPartner()) {
            $dto->partnerIri = $dto->partner = $this->microMapper->map($entity->getPartner(), PartnerApi::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
        }

        if ($entity->getProduct()) {
            $dto->productIri = $dto->product = $this->microMapper->map($entity->getProduct(), ProductApi::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
        }

        $dto->documentObject = $entity->getDocumentObject();
        $dto->documentUrl = $this->fileUrlService->getFileUrl($entity->getDocumentObject());

        $dto->createdBy = $this->microMapper->map($entity->getCreatedBy(), UserApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);
        $dto->createdAt = $entity->getCreatedAt();

        return $dto;
    }
}
