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

declare(strict_types=1);

namespace BookiFlex\Extensions\BackgroundJobs;

use BookiFlex\Core\Contract\ExtensionInterface;
use BookiFlex\Core\Contract\PluginInterface;
use BookiFlex\Extensions\BackgroundJobs\Admin\BackgroundJobsSettings;
use BookiFlex\Extensions\BackgroundJobs\Admin\Notice\QueueDelayedNotice;
use BookiFlex\Extensions\BackgroundJobs\Api\Controller\CronController;
use BookiFlex\Extensions\BackgroundJobs\Service\FallbackRunner;
use BookiFlex\Extensions\BackgroundJobs\Service\HealthChecker;

defined( 'ABSPATH' ) || exit;

/**
 * Background Jobs Extension
 *
 * Ensures ActionScheduler reliability through fallback mechanisms and health monitoring.
 */
class BackgroundJobs implements ExtensionInterface
{
    protected PluginInterface $plugin;

    /**
     * Initialize the extension
     *
     * @param PluginInterface $plugin Plugin instance
     */
    public function init(PluginInterface $plugin): void
    {
        $this->plugin = $plugin;

        // Register ServiceProvider for DI
        $plugin->getContainer()->register(new ServiceProvider());

        // Register settings and controllers
        $plugin->addConfig([
            'settings' => [[
                'tab'     => 'background_jobs',
                'factory' => new BackgroundJobsSettings(
                    $plugin->getContainer()->get(HealthChecker::class)
                ),
                'name'    => __('Background Jobs', 'bookiflex'),
            ]],
            'controllers' => [
                CronController::class,
            ],
        ]);

        // Initialize fallback runner (registers shutdown hook)
        $fallbackRunner = $plugin->getContainer()->get(FallbackRunner::class);
        $fallbackRunner->register($plugin);
    }

    /**
     * Get extension name
     *
     * @return string Extension name
     */
    public function getName(): string
    {
        return 'BackgroundJobs';
    }

    /**
     * Get extension version
     *
     * @return string Extension version
     */
    public function getVersion(): string
    {
        return '1.0.0';
    }

    /**
     * Check if extension is compatible with plugin version
     *
     * @param string $pluginVersion Plugin version
     * @return bool True if compatible
     */
    public function isCompatible(string $pluginVersion): bool
    {
        return version_compare($pluginVersion, '1.0.0', '>=');
    }
}
