<?php

namespace App\Mapper;

use App\ApiResource\UserTripLocationApi;
use App\Entity\UserTripLocation;
use App\Repository\UserTripLocationRepository;
use App\Repository\UserTripRepository;
use App\Repository\LocationRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: UserTripLocationApi::class, to: UserTripLocation::class)]
class UserTripLocationApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private UserTripLocationRepository $repository,
        private UserTripRepository $userTripRepository,
        private LocationRepository $locationRepository,
    ) {
    }

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

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

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

        $userTrip = $this->userTripRepository->find($dto->userTrip->id);
        if (!$userTrip) {
            throw new \Exception('UserTrip not found');
        }

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

        return new UserTripLocation(
            $userTrip,
            $location,
            $dto->plannedDate
        );
    }

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

        $entity->setPlannedDate($dto->plannedDate);

        return $entity;
    }
}
