<?php

namespace Espo\Modules\Sales\Classes\EntityCurrencyConverters;

use Espo\Core\Currency\Rates;
use Espo\Modules\Crm\Entities\Opportunity;
use Espo\Modules\Sales\Entities\QuoteItem;
use Espo\Modules\Sales\Tools\Sales\OrderEntity;
use Espo\ORM\Collection;
use Espo\ORM\Entity;
use Espo\ORM\EntityManager;
use Espo\Tools\Currency\Conversion\DefaultEntityConverter;
use Espo\Tools\Currency\Conversion\EntityConverter;

/**
 * @implements EntityConverter<OrderEntity|Opportunity>
 */
class QuoteConverter implements EntityConverter
{
    public function __construct(
        private DefaultEntityConverter $defaultEntityConverter,
        private EntityManager $entityManager
    ) {}

    public function convert(Entity $entity, string $targetCurrency, Rates $rates): void
    {
        if ($entity instanceof OrderEntity && $entity->isLocked()) {
            return;
        }

        $this->defaultEntityConverter->convert($entity, $targetCurrency, $rates);

        /** @var Collection<QuoteItem> $items */
        $items = $this->entityManager
            ->getRDBRepository($entity->getEntityType())
            ->getRelation($entity, 'items')
            ->find();

        $itemList = [];

        foreach ($items as $item) {
            $this->defaultEntityConverter->convert($item, $targetCurrency, $rates);

            $itemList[] = $item->getValueMap();
        }

        $entity->set('itemList', $itemList);
    }
}
