<?php

namespace App\Mapper;

use App\ApiResource\VesselApi;
use App\Entity\Vessel;
use App\Repository\VesselRepository;
use App\Repository\ShippingCompanyRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;

#[AsMapper(from: VesselApi::class, to: Vessel::class)]
class VesselApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private VesselRepository $repository,
        private ShippingCompanyRepository $shippingCompanyRepository,
    ) {
    }

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

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

        // For new vessels, we need the shipping company
        if (!$dto->companyIri) {
            throw new \Exception('ShippingCompany is required for new vessels');
        }

        $company = $this->shippingCompanyRepository->find($dto->companyIri->id);
        if (!$company) {
            throw new \Exception('ShippingCompany not found');
        }

        return new Vessel($company, $dto->name, $dto->code);
    }

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

        $entity->setName($dto->name);
        $entity->setCode($dto->code);
        $entity->setLength($dto->length);
        $entity->setBreadth($dto->breadth);
        $entity->setDraft($dto->draft);
        $entity->setGrossTonnage($dto->grossTonnage);
        $entity->setImoNo($dto->imoNo);
        $entity->setCallSign($dto->callSign);
        $dto->createdAt = $entity->getCreatedAt();

        return $entity;
    }
}
