<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Cron;

use FiloBlu\Refilo\Model\Importer\Wishlist;
use Magento\Framework\Lock\LockManagerInterface;
use Psr\Log\LoggerInterface;

/**
 * @class WishlistImporterJob
 * @package FiloBlu\Refilo\Cron
 */
class WishlistImporterJob
{

    /** @var string */
    private const LOCK_NAME = 'filoblu_refilo_wishlist_importer';

    /**
     * @var LoggerInterface
     */
    private $logger;
    /**
     * @var Wishlist
     */
    private $wishlist;
    /**
     * @var LockManagerInterface
     */
    private $lockManager;

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

    /**
     * Executes the WishlistImporterJob cron task.
     *
     * This method executes an import of all the MongoDB wishlists in Magento DB, logging any errors encountered
     * during the process
     *
     * @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('[WishlistImporterJob] Another run is in progress, skipping');
            return;
        }

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