<?php

namespace Myvetshop\Module\Clinique\Api\Crokit;

use Doctrine\ORM\EntityManagerInterface;
use Myvetshop\Module\Clinique\Adapter\Recommandation\RecommandationCartRuleRepository;
use Myvetshop\Module\Clinique\Api\Crokit\Dto\CrokitRecommandation;
use Myvetshop\Module\Clinique\Entity\Animal;
use Myvetshop\Module\Clinique\Entity\Factory\RecommandationFactory;
use Myvetshop\Module\Clinique\Entity\Recommandation;
use Myvetshop\Module\Clinique\Repository\AnimalRepository;

class RecommandationImporter
{
    private AnimalRepository $animalRepository;

    private EntityManagerInterface $entityManager;

    private RecommandationFactory $recommandationFactory;

    private RecommandationCartRuleRepository $recommandationCartRuleRepository;

    public function __construct(
        AnimalRepository $animalRepository,
        EntityManagerInterface $entityManager,
        RecommandationFactory $recommandationFactory,
        RecommandationCartRuleRepository $recommandationCartRuleRepository
    ) {
        $this->animalRepository = $animalRepository;
        $this->entityManager = $entityManager;
        $this->recommandationFactory = $recommandationFactory;
        $this->recommandationCartRuleRepository = $recommandationCartRuleRepository;
    }

    public function getRecommandationAnimal(
        string $animalId,
        \Customer $customer,
        CrokitRecommandation $recommandation
    ): Animal {
        if ('auto' === $animalId) {
            $ret = new Animal();
            $ret->idCustomer = (int) $customer->id;
            $ret->espece = $recommandation->esp;
            $ret->nom = $recommandation->petname;
            $ret->idGender = \str_contains(\strtolower($recommandation->sex), 'femel') ? 2 : 1;
            $dobDate = \DateTimeImmutable::createFromFormat('d-m-Y', $recommandation->dob);
            if ($dobDate) {
                $ret->dateNaissance = $dobDate;
            }
            $ret->idProduct = $recommandation->productIDmvs1;
            // TODO : Mettre le bon product_attribute
            $ret->idProductAttribute = 0;
            $ret->ration = $recommandation->qteAliment1;
        } else {
            $ret = $this->animalRepository->findOneBy([
                'id' => $animalId,
                'idCustomer' => (int) $customer->id,
            ]);

            if (!$ret) {
                throw new \Exception('Animal non trouvé');
            }

            \assert($ret instanceof Animal);
        }

        return $ret;
    }

    public function import(
        CrokitRecommandation $recommandationDto,
        Animal $animal
    ): Recommandation {
        $recommandation = $this->recommandationFactory->fromDto($animal, $recommandationDto);

        $this->entityManager->persist($recommandation);
        $this->entityManager->flush();

        // Création du bon de réduction associé
        $this->recommandationCartRuleRepository->createCartRule($recommandation);

        return $recommandation;
    }
}
