<?php
/**
 * WordPress Actions Registration
 *
 * This file registers all WordPress actions for the Zeno Chatbot plugin.
 * Each action is mapped to a handler class for clean separation of concerns.
 *
 * @package ZenoChatbot\Hooks
 */

use ZenoChatbot\Framework\Foundation\Application;
use ZenoChatbot\Support\Hooks;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Register WordPress actions
 *
 * @param Application $app
 * @return void
 *
 */
return function(Application $app) {

    \ZenoChatbot\Services\Scheduler\Scheduler::boot();

    // Frontend Asset Loading
    add_action('wp_enqueue_scripts', function() use ($app) {
        $handler = $app->make(\ZenoChatbot\Hooks\Handler\Frontend\AssetHandler::class);
        $handler->handle();
    });

    // Admin Menu Registration
    add_action('admin_menu', function() use ($app) {
        $handler = $app->make(\ZenoChatbot\Hooks\Handler\Admin\MenuHandler::class);
        $handler->handle();
    });

    // Admin Asset Loading
    add_action('admin_enqueue_scripts', function($hook) use ($app) {
        $handler = $app->make(\ZenoChatbot\Hooks\Handler\Admin\AssetHandler::class);
        $handler->handle($hook);
    });

    // Admin Notices
    add_action('admin_notices', function() use ($app) {
        $handler = $app->make(\ZenoChatbot\Hooks\Handler\Admin\NoticeHandler::class);
        $handler->handle();
    });

    add_action('plugins_loaded', function() use ($app) {
        $handler = $app->make(ZenoChatbot\Hooks\Handler\Plugin\UpgradeHandler::class);
        $handler->handle();
    });

    add_action('init', function() {
        if (\ZenoChatbot\Services\Scheduler\Scheduler::supportsEnsureRecurringActionsHook()) {
            add_action('action_scheduler_ensure_recurring_actions', [\ZenoChatbot\Services\ConversationSummaryWatcher::class, 'ensureMaintenanceScheduled']);
            add_action('action_scheduler_ensure_recurring_actions', [\ZenoChatbot\Services\Scheduler\Scheduler::class, 'ensureCleanupTaskScheduled']);
        }

        \ZenoChatbot\Services\ConversationSummaryWatcher::ensureMaintenanceScheduled();
    });

    Hooks::addAction(Hooks::CONVERSATION_SUMMARY_REQUESTED, function(array $payload) {
        \ZenoChatbot\Services\ConversationSummaryWatcher::handleSummaryRequested($payload);
    });

    add_action(Hooks::CONVERSATION_PROCESS_SUMMARY, function($conversationId = 0, $trigger = 'system') {
        \ZenoChatbot\Services\ConversationSummaryWatcher::processSummaryEvent($conversationId, $trigger);
    }, 10, 2);

    add_action(Hooks::CONVERSATION_MAINTENANCE, function() {
        \ZenoChatbot\Services\ConversationSummaryWatcher::runMaintenance();
    });

    Hooks::addAction(Hooks::INDEX_INTERNAL_UPDATED, function(array $payload) {
        \ZenoChatbot\Services\ContextCache\ResourceTextCache::invalidate('internal-content-index.json');
    });

    Hooks::addAction(Hooks::INDEX_EXTERNAL_UPDATED, function(array $payload) {
        \ZenoChatbot\Services\ContextCache\ResourceTextCache::invalidate('external-sources.json');
    });

    Hooks::addAction(Hooks::INDEX_SITEMAP_UPDATED, function(array $payload) {
        \ZenoChatbot\Services\ContextCache\ResourceTextCache::invalidate('sitemap-content-index.json');
    });

    Hooks::addAction(Hooks::INDEX_PRODUCT_UPDATED, function(array $payload) {
        \ZenoChatbot\Services\ContextCache\ResourceTextCache::invalidate('product-content-index.json');
    });

    Hooks::addAction(Hooks::INDEX_KNOWLEDGE_NOTES_UPDATED, function(array $payload) {
        \ZenoChatbot\Services\ContextCache\ResourceTextCache::invalidate('knowledge-notes-index.json');
    });

    $sitemapSyncLock = \ZenoChatbot\Services\Scheduler\Jobs\SitemapSyncJob::LOCK_KEY;

    add_action(Hooks::INDEX_SITEMAP_SYNC, function() {
        \ZenoChatbot\Services\Scheduler\Jobs\SitemapSyncJob::handle([]);
    });

    $queueSitemapSync = function($postId = 0) use ($sitemapSyncLock) {
        $postId = (int) $postId;
        if ($postId > 0 && (wp_is_post_autosave($postId) || wp_is_post_revision($postId))) {
            return;
        }

        \ZenoChatbot\Services\Scheduler\Scheduler::schedule(Hooks::INDEX_SITEMAP_SYNC, [\ZenoChatbot\Services\Scheduler\Jobs\SitemapSyncJob::class, 'handle'])
            ->group(\ZenoChatbot\Services\Scheduler\Scheduler::defaultGroup())
            ->unique()
            ->when(function() use ($sitemapSyncLock) {
                if (get_transient($sitemapSyncLock)) {
                    return false;
                }

                set_transient($sitemapSyncLock, '1', MINUTE_IN_SECONDS);
                return true;
            })
            ->after(30)
            ->dispatch();
    };

    add_action('save_post', $queueSitemapSync, 20, 1);
    add_action('deleted_post', $queueSitemapSync, 20, 1);
    add_action('trashed_post', $queueSitemapSync, 20, 1);
    add_action('untrashed_post', $queueSitemapSync, 20, 1);
    add_action('transition_post_status', function($newStatus, $oldStatus, $post) use ($queueSitemapSync) {
        if (!($post instanceof \WP_Post)) {
            return;
        }

        if ($newStatus !== $oldStatus) {
            $queueSitemapSync((int) $post->ID);
        }
    }, 20, 3);

};
