<?php

namespace App\Mapper;

use App\ApiResource\ContactApi;
use App\ApiResource\PartnerApi;
use App\ApiResource\PostingApi;
use App\ApiResource\UserApi;
use App\Entity\Contact;
use App\Entity\Posting;
use App\Service\FileUrlService;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: Contact::class, to: ContactApi::class)]
class ContactEntityToApiMapper implements MapperInterface
{
    public function __construct(
        private MicroMapperInterface $microMapper,
        private FileUrlService $fileUrlService
    )
    {
    }

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

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

        return $dto;
    }

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

        $dto->firstName = $entity->getFirstName();
        $dto->lastName = $entity->getLastName();
        $dto->fullName = $entity->getFirstName() . " " . $entity->getLastName();
        $dto->partnerIri = $dto->partner = $this->microMapper->map(
            $entity->getPartner(), PartnerApi::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]
        );
        $dto->birthday = $entity->getBirthday();
        $dto->image = $entity->getImage();
        $dto->imageUrl = $this->fileUrlService->getFileUrl($entity->getImage());
        $dto->position = $entity->getPosition();
        $dto->phone = $entity->getPhone();
        $dto->email = $entity->getEmail();
        $dto->createdBy = $this->microMapper->map($entity->getCreatedBy(), UserApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);
        $dto->createdAt = $entity->getCreatedAt();

        $dto->posts = array_map(function(Posting $posting) {
            return $this->microMapper->map($posting, PostingApi::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
        }, $entity->getPosts()->getValues());

        return $dto;
    }
}
