<?php

namespace App\Mapper;

use App\ApiResource\ContactApi;
use App\ApiResource\PartnerApi;
use App\ApiResource\ProductApi;
use App\ApiResource\SaleApi;
use App\ApiResource\UserApi;
use App\ApiResource\PostingApi;
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->partnerIri = $dto->partner = $this->microMapper->map($entity->getPartner(), PartnerApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);

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

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

        $dto->saleIri = $dto->sale = null;
        if ($entity->getSale() !== null) {
            $dto->saleIri = $dto->sale = $this->microMapper->map($entity->getSale(), SaleApi::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
        }

        $dto->numComments = count($entity->getComments());

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

        return $dto;
    }
}
