<?php

namespace App\Mapper;

use App\ApiResource\ContactApi;
use App\Entity\Contact;
use App\Entity\Partner;
use App\Entity\User;
use App\Repository\ContactRepository;
use App\Repository\PartnerRepository;
use Symfony\Bundle\SecurityBundle\Security;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: ContactApi::class, to: Contact::class)]
class ContactApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private ContactRepository    $repository,
        private Security             $security,
        private MicroMapperInterface $microMapper,
    )
    {

    }

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

        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,
            ]);
            $entity = new Contact($partner, $user);
        }


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

        return $entity;
    }

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

        $entity->setFirstName($dto->firstName);
        $entity->setLastName($dto->lastName);
        $entity->setBirthday($dto->birthday);
        $entity->setImage($dto->image);
        $entity->setPosition($dto->position);
        $entity->setPhone($dto->phone);
        $entity->setEmail($dto->email);

        return $entity;
    }
}
