<?php

namespace App\Mapper;

use App\ApiResource\TaskNoteApi;
use App\Entity\Contact;
use App\Entity\Task;
use App\Entity\TaskNote;
use App\Entity\User;
use App\Repository\TaskNoteRepository;
use Symfony\Bundle\SecurityBundle\Security;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: TaskNoteApi::class, to: TaskNote::class)]
class TaskNoteApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private TaskNoteRepository   $repository,
        private Security             $security,
        private MicroMapperInterface $microMapper,
    )
    {

    }

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

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

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

        return $entity;
    }

    public function populate(object $from, object $to, array $context): object
    {
        $dto = $from;
        assert($dto instanceof TaskNoteApi);
        $entity = $to;
        assert($entity instanceof TaskNote);
        $entity->setMessage($dto->message);
        $entity->setType($dto->contactType);
        if ($dto->contactIri) {
            $entity->setContact($this->microMapper->map($dto->contactIri, Contact::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]));
        }


        return $entity;
    }
}
