<?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\Partner;
use App\Entity\Posting;
use App\Service\FileUrlService;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;
use Vich\UploaderBundle\Storage\StorageInterface;

#[AsMapper(from: Partner::class, to: PartnerApi::class)]
class PartnerEntityToApiMapper 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 Partner);

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

        return $dto;
    }

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

        $dto->name = $entity->getName();
        $dto->partnerType = $entity->getType();
        $dto->description = $entity->getDescription();
        $dto->street = $entity->getStreet();
        $dto->streetNo = $entity->getStreetNo();
        $dto->zip = $entity->getZip();
        $dto->city = $entity->getCity();
        $dto->country = $entity->getCountry();
        $dto->website = $entity->getWebsite();
        $dto->logo = $entity->getLogo();
        $dto->logoUrl = $this->fileUrlService->getFileUrl($entity->getLogo());
        $dto->createdBy = $this->microMapper->map($entity->getCreatedBy(), UserApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);
        $dto->createdByName = $entity->getCreatedBy()?->getFirstName() . ' ' . $entity->getCreatedBy()?->getLastName();
        $dto->createdAt = $entity->getCreatedAt();
        $dto->posts = array_map(function(Posting $posting) {
            return $this->microMapper->map($posting, PostingApi::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
        }, $entity->getPostings()->getValues());
        $dto->contacts = array_map(function(Contact $contact) {
            return $this->microMapper->map($contact, ContactApi::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
        }, $entity->getContacts()->getValues());
        return $dto;
    }
}
