<?php

namespace App\Mapper;

use App\ApiResource\LocationApi;
use App\Entity\Location;
use App\Repository\LocationRepository;
use App\Repository\ZoneRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: LocationApi::class, to: Location::class)]
class LocationApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private LocationRepository $repository,
        private ZoneRepository $zoneRepository,
    ) {
    }

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

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

        if (!$dto->zoneIri) {
            throw new \Exception('Zone is required for new locations');
        }

        $zone = $this->zoneRepository->find($dto->zoneIri->id);
        if (!$zone) {
            throw new \Exception('Zone not found');
        }

        return new Location($zone, $dto->name, $dto->code);
    }

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

        $entity->setName($dto->name);
        $entity->setCode($dto->code);
        $entity->setIsZone($dto->isZone);
        $entity->setIsPlace($dto->isPlace);
        $entity->setIsPort($dto->isPort);
        $entity->setIsStartEnd($dto->isStartEnd);

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

        return $entity;
    }
}