<?php

namespace App\Mapper;

use App\ApiResource\MediaObjectApi;
use App\ApiResource\TripApi;
use App\ApiResource\UserApi;
use App\ApiResource\UserTripApi;
use App\Entity\UserTrip;
use App\Service\FileUrlService;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: UserTrip::class, to: UserTripApi::class)]
class UserTripEntityToApiMapper implements MapperInterface
{
    public function __construct(
        private MicroMapperInterface $microMapper,
        private FileUrlService $fileUrlService
    ) {
    }

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

        $dto = new UserTripApi();
        $dto->id = $entity->getId();

        return $dto;
    }

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

        $dto->dbId = $entity->getId();
        $dto->captainName = $entity->getCaptainName();
        $dto->signatureUrl = $this->fileUrlService->getFileUrl($entity->getSignature());
        $dto->completed = $entity->isCompleted();
        $dto->approved = $entity->isApproved();
        $dto->completedDate = $entity->getCompletedDate();
        $dto->createdAt = $entity->getCreatedAt();

        $dto->tripIri = $dto->trip = $this->microMapper->map($entity->getTrip(), TripApi::class, [
            MicroMapperInterface::MAX_DEPTH => 5,
        ]);

        $dto->userIri = $dto->user = $this->microMapper->map($entity->getUser(), UserApi::class, [
            MicroMapperInterface::MAX_DEPTH => 5,
        ]);

        $dto->signatureIri = $dto->signature = null;
        if ($entity->getSignature() !== null) {
            $dto->signatureIri = $dto->signature = $this->microMapper->map($entity->getSignature(), MediaObjectApi::class, [
                MicroMapperInterface::MAX_DEPTH => 5,
            ]);
        }

        return $dto;
    }
}