<?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\Repository\CatalogChangeRepository;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
final readonly class PurgeCatalogChangesMessageHandler
{
    public function __construct(
        private CatalogChangeRepository $repository,
        private ?LoggerInterface $logger = null,
    ) {}

    public function __invoke(PurgeCatalogChangesMessage $message): void
    {
        $retentionDays = max(30, min(3650, $message->retentionDays));
        $before = new \DateTimeImmutable('now', new \DateTimeZone('UTC'))
            ->sub(new \DateInterval('P' . $retentionDays . 'D'));
        $deleted = $this->repository->purgeCompletedBefore($before);

        if ($deleted > 0) {
            $this->logger?->info('Anciens changements Commerce purgés.', [
                'count' => $deleted,
                'retention_days' => $retentionDays,
            ]);
        }
    }
}
