<?php

namespace App\Mapper;

use App\ApiResource\UserTripWorkLogApi;
use App\Entity\UserTripWorkLog;
use App\Repository\UserTripWorkLogRepository;
use App\Repository\UserTripRepository;
use App\Repository\LocationRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: UserTripWorkLogApi::class, to: UserTripWorkLog::class)]
class UserTripWorkLogApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private UserTripWorkLogRepository $repository,
        private UserTripRepository $userTripRepository,
        private LocationRepository $locationRepository,
    ) {
    }

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

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

        // For new work logs, we need userTrip and both locations
        if (!$dto->userTrip?->id || !$dto->startLocation?->id || !$dto->endLocation?->id) {
            throw new \Exception('UserTrip, start location and end location are required for new work logs');
        }

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

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

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

        return new UserTripWorkLog(
            $userTrip,
            $startLocation,
            $endLocation,
            $dto->startDate,
            $dto->endDate
        );
    }

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

        $entity->setStartDate($dto->startDate);
        $entity->setEndDate($dto->endDate);

        return $entity;
    }
}