<?php

namespace App\Mapper;

use App\ApiResource\UserTripApi;
use App\Entity\Trip;
use App\Entity\User;
use App\Entity\UserTrip;
use App\Repository\MediaObjectRepository;
use App\Repository\UserTripRepository;
use App\Repository\TripRepository;
use App\Repository\UserRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: UserTripApi::class, to: UserTrip::class)]
class UserTripApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private UserTripRepository $repository,
        private TripRepository $tripRepository,
        private UserRepository $userRepository,
        private MediaObjectRepository $mediaObjectRepository,
        private MicroMapperInterface $microMapper
    ) {
    }

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

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

        // For new user trips, we need trip and user
        if (!$dto->tripIri || !$dto->userIri) {
            throw new \Exception('Trip and User are required for new user trips');
        }

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

        $user = $this->userRepository->find($dto->userIri->id);
        if (!$user) {
            throw new \Exception('User not found');
        }

        return new UserTrip($trip, $user);
    }

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

        $entity->setCaptainName($dto->captainName);

        if ($dto->completed && $entity->getCompletedDate() === null) {
            $entity->setCompletedDate(new \DateTimeImmutable());
        }
        $entity->setCompleted($dto->completed);
        $entity->setApproved($dto->approved);

        if ($dto->signatureIri) {
            $signature = $this->mediaObjectRepository->find($dto->signatureIri->id);
            if (!$signature) {
                throw new \Exception('Signature not found');
            }
            $entity->setSignature($signature);
        } else {
            $entity->setSignature(null);
        }

        return $entity;
    }
}