<?php

namespace App\Mapper;

use App\ApiResource\CommentApi;
use App\ApiResource\SaleApi;
use App\Entity\Comment;
use App\Entity\Partner;
use App\Entity\Product;
use App\Entity\Sale;
use App\Entity\User;
use App\Repository\SaleRepository;
use Symfony\Bundle\SecurityBundle\Security;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: SaleApi::class, to: Sale::class)]
class SaleApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private SaleRepository       $repository,
        private Security             $security,
        private MicroMapperInterface $microMapper,
    )
    {

    }

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

        if ($dto->id) {
            $entity = $this->repository->find($dto->id);
        } else {
            $user = $this->security->getUser();
            assert($user instanceof User);
            if ($dto->partnerIri === null) {
                throw new \Exception('Partner missing');
            }
            $partner = $this->microMapper->map($dto->partnerIri, Partner::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
            if ($dto->productIri === null) {
                throw new \Exception('Product missing');
            }
            $product = $this->microMapper->map($dto->productIri, Product::class, [
                MicroMapperInterface::MAX_DEPTH => 1,
            ]);
            assert($partner instanceof Partner);
            assert($product instanceof Product);
            $entity = new Sale($user, $partner, $product);
        }

        if (!$entity) {
            throw new \Exception('Sale not found');
        }

        return $entity;
    }

    public function populate(object $from, object $to, array $context): object
    {
        $dto = $from;
        assert($dto instanceof SaleApi);
        $entity = $to;
        assert($entity instanceof Sale);
        $entity->setTurnover($dto->turnover);
        $entity->setProfit($dto->profit);
        $entity->setQuantity($dto->quantity);
        $entity->setComment($dto->comment);

        return $entity;
    }
}
