<?php
/**
 * BookiFlex Cart Extension
 *
 * @package    BookiFlex
 * @subpackage Cart
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */


declare(strict_types=1);
namespace BookiFlex\Extensions\Cart;

use BookiFlex\Core\Contract\ExtensionInterface;
use BookiFlex\Core\Contract\PluginInterface;
use BookiFlex\Extensions\Cart\Api\Controller\CartController;
use BookiFlex\Extensions\Cart\ORM\CartSchema;
use BookiFlex\Extensions\Cart\Service\Jobs\CleanupExpiredCartsJob;

defined( 'ABSPATH' ) || exit;

class Cart implements ExtensionInterface
{
    protected PluginInterface $plugin;

    public function init(PluginInterface $plugin): void
    {
        $this->plugin = $plugin;
        $plugin->getContainer()->register(new ServiceProvider());

        $plugin->addConfig([
            'schemas' => [
                CartSchema::class,
            ],
            'controllers' => [
                CartController::class,
            ],
            'subscribers' => [],
        ]);

        $this->registerQueueHandlers();
    }

    private function registerQueueHandlers(): void
    {
        $this->plugin->addAction(
            CleanupExpiredCartsJob::HOOK,
            [$this, 'handleCleanupExpiredCarts'],
            10,
            1
        );
    }

    public function handleCleanupExpiredCarts($args = []): void
    {
        $job = $this->plugin->getContainer()->get(CleanupExpiredCartsJob::class);

        if (is_array($args)) {
            $job->handle($args);
        } else {
            $this->plugin->getLogger()?->warning(
                'Invalid args passed to ' . CleanupExpiredCartsJob::HOOK,
                ['args' => $args]
            );
        }
    }

    public function getName(): string
    {
        return 'Cart';
    }

    public function getVersion(): string
    {
        return '1.0.0';
    }

    public function isCompatible(string $pluginVersion): bool
    {
        return version_compare($pluginVersion, '1.0.0', '>=');
    }
}
