<?php

namespace App\Mapper;

use App\ApiResource\LocationApi;
use App\ApiResource\TripApi;
use App\ApiResource\VesselApi;
use App\Entity\Trip;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: Trip::class, to: TripApi::class)]
class TripEntityToApiMapper implements MapperInterface
{
    public function __construct(
        private MicroMapperInterface $microMapper
    ) {
    }

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

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

        return $dto;
    }

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

        $dto->dbId = $entity->getId();
        $dto->pilotageReference = "P-" . $entity->getId() . "-" . $entity->getStartDate()->format('Y');
        $dto->startDate = $entity->getStartDate();
        $dto->endDate = $entity->getEndDate();
        $dto->note = $entity->getNote();
        $dto->completed = $entity->isCompleted();
        $dto->createdAt = $entity->getCreatedAt();

        // Map related entities
        $dto->vesselIri = $dto->vessel = $this->microMapper->map($entity->getVessel(), VesselApi::class, [
            MicroMapperInterface::MAX_DEPTH => 5,
        ]);

        $dto->startLocationIri = $dto->startLocation = $this->microMapper->map($entity->getStartLocation(), LocationApi::class, [
            MicroMapperInterface::MAX_DEPTH => 5,
        ]);

        $dto->endLocationIri = $dto->endLocation = $this->microMapper->map($entity->getEndLocation(), LocationApi::class, [
            MicroMapperInterface::MAX_DEPTH => 5,
        ]);

        return $dto;
    }
}