<?php

namespace WPSN\Modules\Audit;

use WPSN\Core\AbstractModule;

defined('ABSPATH') || exit;

/**
 * Stage 8: Minimal rule-based audit (issues list + scan).
 */
final class AuditModule extends AbstractModule
{
    public function id(): string
    {
        return 'audit';
    }

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

    public function description(): string
    {
        return __('Rule-based SEO audit (missing meta, duplicates, noindex, canonical issues).', 'wp-seo-next');
    }

    public function defaultEnabled(): bool
    {
        // Enabled by default since it is a lightweight admin-only feature.
        return true;
    }

    public function register(): void
    {
        // Ensure DB table exists.
        add_action('init', [AuditInstaller::class, 'maybeInstall'], 1);

        // Queue handlers (async scans).
        /** @var \WPSN\SEO\SeoMetaRepository $metaRepo */
        $metaRepo = $this->container->get('meta_repo');

        $issues = new AuditIssueRepository($this->logger);
        $scans = new AuditScanRepository($this->logger);
        $scanIssues = new AuditScanIssueRepository($this->logger);
        $titleKeys = new AuditTitleKeyRepository($this->logger);
        $descKeys = new AuditDescriptionKeyRepository($this->logger);

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

        $jobs = new AuditJobs($metaRepo, $issues, $scans, $scanIssues, $titleKeys, $descKeys, $queue, $this->settings, $this->logger);

        // Synchronous SQL scan mode (no queue/cron).
        $sqlScanner = new AuditSqlScanner($issues, $scans, $scanIssues, $this->settings, $this->logger);

        // Optional scheduled scans.
        (new AuditAutomation($jobs, $this->settings, $this->logger, $queue))->register();

        add_filter('wpsn_queue_handle_' . AuditJobs::JOB_SCAN_DISPATCH, [$jobs, 'handleDispatch'], 10, 3);
        add_filter('wpsn_queue_handle_' . AuditJobs::JOB_SCAN_POSTS, [$jobs, 'handleScanPosts'], 10, 3);
        add_filter('wpsn_queue_handle_' . AuditJobs::JOB_SCAN_TERMS, [$jobs, 'handleScanTerms'], 10, 3);
        add_filter('wpsn_queue_handle_' . AuditJobs::JOB_SCAN_FINALIZE, [$jobs, 'handleFinalize'], 10, 3);
        add_filter('wpsn_queue_handle_' . AuditJobs::JOB_BULK_FIX, [$jobs, 'handleBulkFix'], 10, 3);
        add_filter('wpsn_queue_handle_' . AuditJobs::JOB_REFRESH_OBJECT_ISSUES, [$jobs, 'handleRefreshObjectIssues'], 10, 3);

        if (is_admin()) {
            /** @var \WPSN\Core\Queue\QueueRunner $queueRunner */
            $queueRunner = $this->container->get('queue_runner');

            $admin = new Admin\AuditAdmin($issues, $scans, $scanIssues, $jobs, $sqlScanner, $queueRunner, $this->logger);
            $admin->register();
        }
    }
}
