<?php

namespace App\Mapper;

use App\ApiResource\PartnerFollowApi;
use App\Entity\Partner;
use App\Entity\PartnerFollow;
use App\Entity\User;
use App\Repository\PartnerFollowRepository;
use Symfony\Bundle\SecurityBundle\Security;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: PartnerFollowApi::class, to: PartnerFollow::class)]
class PartnerFollowApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private PartnerFollowRepository    $repository,
        private Security             $security,
        private MicroMapperInterface $microMapper,
    )
    {

    }

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

        if ($dto->id) {
            $entity = $this->repository->find($dto->id);
        } else {
            $user = $this->security->getUser();
            assert($user instanceof User);
            if ($dto->partnerIri === null) {
                throw new \Exception('Partner missing');
            }
            $partner = $this->microMapper->map($dto->partnerIri, Partner::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
            assert($partner instanceof Partner);
            $entity = new PartnerFollow($user, $partner);
        }

        if (!$entity) {
            throw new \Exception('PartnerFollow not found');
        }

        return $entity;
    }

    public function populate(object $from, object $to, array $context): object
    {
        $dto = $from;
        assert($dto instanceof PartnerFollowApi);
        $entity = $to;
        assert($entity instanceof PartnerFollow);
        return $entity;
    }
}
