<?php

namespace App\Mapper;

use App\ApiResource\EventApi;
use App\Entity\Event;
use App\Repository\EventRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;

#[AsMapper(from: EventApi::class, to: Event::class)]
class EventApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private EventRepository $repository,
    ) {
    }

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

        if ($dto->id) {
            $entity = $this->repository->find($dto->id);
            if (!$entity) {
                throw new \Exception('Event not found');
            }
            return $entity;
        }

        return new Event();
    }

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

        $entity->setName($dto->name);
        $entity->setIdentifier($dto->identifier);
        $entity->setSequence($dto->sequence);
        $entity->setMandatory($dto->mandatory);

        return $entity;
    }
}