<?php

namespace App\Mapper;

use App\ApiResource\CommentApi;
use App\Entity\Comment;
use App\Entity\Posting;
use App\Entity\User;
use App\Repository\CommentRepository;
use Symfony\Bundle\SecurityBundle\Security;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: CommentApi::class, to: Comment::class)]
class CommentApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private CommentRepository    $repository,
        private Security             $security,
        private MicroMapperInterface $microMapper,
    )
    {

    }

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

        if ($dto->id) {
            $entity = $this->repository->find($dto->id);
        } else {
            $user = $this->security->getUser();
            assert($user instanceof User);
            if ($dto->postIri === null) {
                throw new \Exception('Posting missing');
            }
            $posting = $this->microMapper->map($dto->postIri, Posting::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
            assert($posting instanceof Posting);
            $entity = new Comment($user, $posting);
        }

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

        return $entity;
    }

    public function populate(object $from, object $to, array $context): object
    {
        $dto = $from;
        assert($dto instanceof CommentApi);
        $entity = $to;
        assert($entity instanceof Comment);
        $entity->setMessage($dto->message);
        return $entity;
    }
}
