<?php

namespace App\Mapper;

use App\ApiResource\UserTripEventApi;
use App\Entity\UserTripEvent;
use App\Repository\UserTripEventRepository;
use App\Repository\UserTripRepository;
use App\Repository\EventRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: UserTripEventApi::class, to: UserTripEvent::class)]
class UserTripEventApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private UserTripEventRepository $repository,
        private UserTripRepository $userTripRepository,
        private EventRepository $eventRepository,
    ) {
    }

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

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

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

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

        $event = $this->eventRepository->find($dto->event->id);
        if (!$event) {
            throw new \Exception('Event not found');
        }

        return new UserTripEvent($userTrip, $event, $dto->date);
    }

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

        if ($dto->event) {
            $event = $this->eventRepository->find($dto->event->id);
            if (!$event) {
                throw new \Exception('Event not found');
            }
            $entity->setEvent($event);
        }

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

        $entity->setNote($dto->note);
        $entity->setDate($dto->date);

        return $entity;
    }
}