<?php

namespace Myvetshop\Module\Clinique\Prestashop\Hook;

use Doctrine\ORM\EntityManagerInterface;
use Myvetshop\Module\Clinique\Adapter\Hook\ActionObjectCustomerAddAfterInterface;
use Myvetshop\Module\Clinique\Adapter\PrestashopLoggerAdapter;
use Myvetshop\Module\Clinique\Entity\EstablishmentEvent;
use Myvetshop\Module\Clinique\Entity\Factory\EstablishmentEventFactory;

class EstablishmentEventListener implements ActionObjectCustomerAddAfterInterface
{
    private EntityManagerInterface $entityManager;

    private EstablishmentEventFactory $establishmentEventFactory;

    private PrestashopLoggerAdapter $prestashopLoggerAdapter;

    public function __construct(
        EntityManagerInterface $entityManager,
        EstablishmentEventFactory $establishmentEventFactory,
        PrestashopLoggerAdapter $prestashopLoggerAdapter
    ) {
        $this->entityManager = $entityManager;
        $this->establishmentEventFactory = $establishmentEventFactory;
        $this->prestashopLoggerAdapter = $prestashopLoggerAdapter;
    }

    public function actionObjectCustomerAddAfter(\Customer $customer): void
    {
        if ((int) $customer->id_default_group !== 3) {
            // Add join event
            try {
                $event = $this->establishmentEventFactory->createCustomerEvent(
                    EstablishmentEvent::EVENT_CUSTOMER_JOIN,
                    $customer
                );

                $this->entityManager->persist($event);
                $this->entityManager->flush();
            } catch (\Exception $e) {
                // Log error
                $this->prestashopLoggerAdapter->error(
                    $e->getMessage(),
                    [
                        'errorCode' => $e->getCode(),
                        'objectType' => 'EstablishmentEvent',
                        'stackTrace' => $e->getTraceAsString(),
                    ]
                );
            }
        }
    }
}
