<?php

namespace WPSN\Modules\Media;

use WPSN\Core\AbstractModule;
use WPSN\Core\Queue\QueueInterface;
use WPSN\Core\Queue\QueueRunner;
use WPSN\Modules\AI\AIInstaller;
use WPSN\Modules\Media\Admin\MediaAdmin;

defined('ABSPATH') || exit;

/**
 * Media SEO: bulk alt text drafts (local/OpenAI) + safe apply/undo.
 */
final class MediaModule extends AbstractModule
{
    public function id(): string
    {
        return 'media';
    }

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

    public function description(): string
    {
        return __('Bulk generate image alt text drafts (local/OpenAI) and apply/undo them.', 'wp-seo-next');
    }

    public function defaultEnabled(): bool
    {
        return true;
    }

    public function register(): void
    {
        // Ensure AI logs table exists even if AI module is disabled (Media 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 MediaJobs($this->settings, $this->logger);

        $filenameJobs = new MediaFilenameJobs($this->settings, $this->logger);

        // Queue job handlers (optional; admin UI can choose to enqueue later).
        add_filter('wpsn_queue_handle_media_alt_generate', [$jobs, 'handleGenerateAlt'], 10, 3);
        add_filter('wpsn_queue_handle_media_alt_apply', [$jobs, 'handleApplyAlt'], 10, 3);

        // Filename cleanup draft/apply.
        add_filter('wpsn_queue_handle_media_filename_generate', [$filenameJobs, 'handleGenerateFilename'], 10, 3);
        add_filter('wpsn_queue_handle_media_filename_apply', [$filenameJobs, 'handleApplyFilename'], 10, 3);

        if (is_admin()) {
            (new MediaAdmin($queue, $runner, $this->settings, $this->logger))->register();
        }
    }
}
