<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Cron;

use FiloBlu\Refilo\Model\Deleter\ItemCleaner;
use Magento\Framework\Lock\LockManagerInterface;
use Psr\Log\LoggerInterface;

class BeehiveCleanerJob
{
    /** @var string */
    private const LOCK_NAME = 'filoblu_refilo_beehive_cleaner';

    /**
     * @var ItemCleaner
     */
    private $itemCleaner;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var LockManagerInterface
     */
    private $lockManager;

    /**
     * @param ItemCleaner $itemCleaner
     * @param LoggerInterface $logger
     * @param LockManagerInterface $lockManager
     */
    public function __construct(
        ItemCleaner     $itemCleaner,
        LoggerInterface $logger,
        LockManagerInterface $lockManager
    )
    {
        $this->itemCleaner = $itemCleaner;
        $this->logger = $logger;
        $this->lockManager = $lockManager;
    }

    /**
     * Executes the BeehiveCleanerJob cron task.
     *
     * This method logs the start of the cron job, invokes the item cleaner to clean deleted items
     * for all configured indexers, and logs the completion or any errors encountered during execution.
     *
     * @return void
     */
    public function execute()
    {
        // Try to acquire the lock without waiting; skip if a previous run is still in progress.
        if (!$this->lockManager->lock(self::LOCK_NAME, 0)) {
            $this->logger->info('[BeehiveCleanerJob] Another run is in progress, skipping');
            return;
        }

        try {
            $this->logger->info('[BeehiveCleanerJob] Cron started');
            $this->itemCleaner->clean();
            $this->logger->info('[BeehiveCleanerJob] Cron completed successfully');
        } catch (\Throwable $e) {
            $this->logger->error('[BeehiveCleanerJob] Cron failed: ' . $e->getMessage());
            $this->logger->error($e->getTraceAsString());
        } finally {
            $this->lockManager->unlock(self::LOCK_NAME);
        }
    }
}
