<?php

namespace WPSN\Modules\Bulk;

use WPSN\Core\AbstractModule;
use WPSN\Core\Queue\QueueInterface;
use WPSN\Core\Queue\QueueRunner;
use WPSN\Modules\AI\AIInstaller;
use WPSN\Modules\Bulk\Admin\BulkAdmin;

defined('ABSPATH') || exit;

/**
 * Stage 11: Bulk optimization (draft suggestions) + DB-backed queue worker.
 */
final class BulkModule extends AbstractModule
{
    public function id(): string
    {
        return 'bulk';
    }

    public function name(): string
    {
        return __('Bulk Optimize', 'wp-seo-next');
    }

    public function description(): string
    {
        return __('Generate SEO suggestions in bulk (drafts) and apply/undo them safely via queue.', 'wp-seo-next');
    }

    public function defaultEnabled(): bool
    {
        // Admin-only feature; safe to enable by default.
        return true;
    }

    public function register(): void
    {
        // Ensure AI logs table exists even if AI module is disabled (Bulk can use OpenAI).
        add_action('init', [AIInstaller::class, 'maybeInstall'], 1);

        /** @var QueueInterface $queue */
        $queue = $this->container->get('queue');

        /** @var QueueRunner $runner */
        $runner = $this->container->get('queue_runner');

        $jobs = new BulkJobs($this->settings, $this->logger, $queue);
        $tracker = new BulkQueueSessionTracker($this->logger);

        // Queue job handlers.
        add_filter('wpsn_queue_handle_bulk_generate', [$jobs, 'handleGenerate'], 10, 3);
        add_filter('wpsn_queue_handle_bulk_apply', [$jobs, 'handleApply'], 10, 3);
        $tracker->register();

        // Admin UI.
        if (is_admin()) {
            (new BulkAdmin($queue, $runner, $this->settings, $this->logger))->register();
        }
    }
}
