<?php

namespace App\Mapper;

use App\ApiResource\CommentApi;
use App\ApiResource\UserApi;
use App\ApiResource\PostingApi;
use App\Entity\Comment;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: Comment::class, to: CommentApi::class)]
class CommentEntityToApiMapper implements MapperInterface
{
    public function __construct(
        private MicroMapperInterface $microMapper
    )
    {
    }

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

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

        return $dto;
    }

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

        $dto->message = $entity->getMessage();
        $dto->owner = $this->microMapper->map($entity->getOwner(), UserApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);

        $dto->postIri = $this->microMapper->map($entity->getPosting(), PostingApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);

        $dto->createdAt = $entity->getCreatedAt();

        return $dto;
    }
}
