<?php

namespace App\Mapper;

use App\ApiResource\CommentApi;
use App\ApiResource\ContactApi;
use App\ApiResource\PartnerApi;
use App\ApiResource\ProductApi;
use App\ApiResource\UserApi;
use App\ApiResource\PostingApi;
use App\Entity\Comment;
use App\Entity\Posting;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: Posting::class, to: PostingApi::class)]
class PostingEntityToApiMapper implements MapperInterface
{
    public function __construct(
        private MicroMapperInterface $microMapper,
    )
    {
    }

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

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

        return $dto;
    }

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

        $dto->headline = $entity->getHeadline();
        $dto->message = $entity->getMessage();
        $dto->owner = $this->microMapper->map($entity->getOwner(), UserApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);
        $dto->ownerName = $entity->getOwner()?->getFirstName()." ".$entity->getOwner()?->getLastName();

        $dto->partner = $this->microMapper->map($entity->getPartner(), PartnerApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);
        $dto->partnerName = $entity->getPartner()?->getName();

        $dto->product = $this->microMapper->map($entity->getProduct(), ProductApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);
        $dto->productName = $entity->getProduct()?->getName();

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

        $dto->comments = array_map(function(Comment $comment) {
            return $this->microMapper->map($comment, CommentApi::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
        }, $entity->getComments()->getValues());

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

        return $dto;
    }
}
