<?php
namespace App\Mapper;

use App\ApiResource\ShippingCompanyApi;
use App\Entity\ShippingCompany;
use App\Repository\ShippingCompanyRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: ShippingCompanyApi::class, to: ShippingCompany::class)]
class ShippingCompanyApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private ShippingCompanyRepository $repository,
    ) {
    }

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

        $entity = $dto->id ? $this->repository->find($dto->id) : new ShippingCompany($dto->name, $dto->code);
        if ($dto->id && !$entity) {
            throw new \Exception('ShippingCompany not found');
        }

        return $entity;
    }

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

        $entity->setName($dto->name);
        $entity->setCode($dto->code);

        return $entity;
    }
}