<?php

namespace App\Mapper;

use App\ApiResource\ZoneApi;
use App\Entity\Zone;
use App\Repository\ZoneRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;

#[AsMapper(from: ZoneApi::class, to: Zone::class)]
class ZoneApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private ZoneRepository $repository,
    ) {
    }

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

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

        return new Zone($dto->name);
    }

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

        $entity->setName($dto->name);

        return $entity;
    }
}