<?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\Bridge\Symfony\Bundle\Scheduler;

use CpCreation\VitiCore\Cart\CartAbandonmentMarker;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
final readonly class MarkAbandonedCartsMessageHandler
{
    public function __construct(
        private CartAbandonmentMarker $cartAbandonmentMarker,
        private ?LoggerInterface $logger = null,
    ) {
    }

    public function __invoke(MarkAbandonedCartsMessage $message): void
    {
        $result = $this->cartAbandonmentMarker->mark(
            pendingAfterHours: $message->pendingAfterHours,
            checkoutAfterHours: $message->checkoutAfterHours,
            limit: $message->limit,
        );

        if ($result->markedCount > 0) {
            $this->logger?->info('Paniers abandonnes marques par le scheduler.', [
                'marked_count' => $result->markedCount,
                'eligible_count' => \count($result->eligibleCarts),
                'pending_cutoff' => $result->pendingCutoff->format(\DATE_ATOM),
                'checkout_cutoff' => $result->checkoutCutoff->format(\DATE_ATOM),
            ]);
        }
    }
}
