<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Commerce\Catalog\Outbox\Message;

use CpCreation\VitiCore\Commerce\Catalog\Configuration\CatalogIntegrationConfiguration;
use CpCreation\VitiCore\Commerce\Catalog\Configuration\CatalogWebhookEndpointResolver;
use CpCreation\VitiCore\Commerce\Catalog\Model\CatalogChange;
use CpCreation\VitiCore\Commerce\Catalog\Model\CatalogChangeType;
use CpCreation\VitiCore\Commerce\Catalog\Model\CatalogResourceType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
final readonly class ReconcileCatalogStockMessageHandler
{
    public function __construct(
        private CatalogIntegrationConfiguration $configuration,
        private CatalogWebhookEndpointResolver $webhookEndpointResolver,
        private EntityManagerInterface $entityManager,
    ) {}

    public function __invoke(ReconcileCatalogStockMessage $message): void
    {
        if (!$this->webhookEndpointResolver->isReady()) {
            return;
        }

        $this->entityManager->persist(new CatalogChange(
            instanceId: $this->configuration->instanceId(),
            type: CatalogChangeType::RECONCILIATION_REQUIRED,
            resourceType: CatalogResourceType::CATALOG,
            resourceId: null,
            occurredAt: new \DateTimeImmutable('now', new \DateTimeZone('UTC')),
        ));
        $this->entityManager->flush();
    }
}
