<?php

namespace App\Mapper;

use App\ApiResource\ContactApi;
use App\ApiResource\TaskApi;
use App\ApiResource\TaskNoteApi;
use App\ApiResource\UserApi;
use App\Entity\TaskNote;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: TaskNote::class, to: TaskNoteApi::class)]
class TaskNoteEntityToApiMapper implements MapperInterface
{
    public function __construct(
        private MicroMapperInterface $microMapper
    )
    {
    }

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

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

        return $dto;
    }

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

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

        $dto->taskIri = $this->microMapper->map($entity->getTask(), TaskApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);

        if ($entity->getContact() !== null) {
            $dto->contact = $this->microMapper->map($entity->getContact(), ContactApi::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);

            $dto->contactIri = $this->microMapper->map($entity->getContact(), ContactApi::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
        }

        $dto->contactType = $entity->getType();

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

        return $dto;
    }
}
