<?php

namespace App\Mapper;

use App\ApiResource\TripLocationApi;
use App\Entity\TripLocation;
use App\Repository\TripLocationRepository;
use App\Repository\TripRepository;
use App\Repository\LocationRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: TripLocationApi::class, to: TripLocation::class)]
class TripLocationApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private TripLocationRepository $repository,
        private TripRepository $tripRepository,
        private LocationRepository $locationRepository,
    ) {
    }

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

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

        // For new trip locations, we need trip and location
        if (!$dto->tripIri->id || !$dto->locationIri->id) {
            throw new \Exception('Trip and Location are required for new trip locations');
        }

        $trip = $this->tripRepository->find($dto->tripIri->id);
        if (!$trip) {
            throw new \Exception('Trip not found');
        }

        $location = $this->locationRepository->find($dto->locationIri->id);
        if (!$location) {
            throw new \Exception('Location not found');
        }

        return new TripLocation($trip, $location);
    }

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

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

        $entity->setArrivalDateTime($dto->arrivalDateTime);
        $entity->setDepartureDateTime($dto->departureDateTime);

        return $entity;
    }
}