<?php
declare(strict_types=1);

namespace Ekesto\CacheInvalidator\Integrations\Caching;

use Ekesto\CacheInvalidator\Core\EmissionHelper;
use Ekesto\CacheInvalidator\Core\GlobalInvalidationExecutor;
use Ekesto\CacheInvalidator\Support\Debug;

/**
 * Shared system-trigger emission helper for cache-plugin full clear events.
 */
trait EmitsFullInvalidationFromCacheClear
{
    /**
     * Emit a GLOBAL_INVALIDATION event when a cache plugin reports a full clear.
     *
     * @param string $source Adapter source identifier.
     * @return void
     */
    private function emitFullInvalidationFromCacheClear(string $source): void
    {
        $hook = (string) current_filter();
        if (!AdapterSignalGuard::shouldProcessSignal($source, $hook, 'global_invalidation')) {
            return;
        }

        Debug::log('cache_plugin_clear_detected', [
            'source' => sanitize_key($source),
            'hook' => $hook,
        ]);

        GlobalInvalidationExecutor::markGlobalInvalidationRun();

        EmissionHelper::emit([], [
            'trigger_class' => 'system',
            'trigger_event' => 'cache_plugin_cleared',
            'trigger_post_id' => 0,
            'trigger_post_type' => '',
            'reason' => 'cache_plugin_clear',
            'resolution' => 'GLOBAL_INVALIDATION',
            'intent' => 'GLOBAL_INVALIDATION',
            'source' => sanitize_key($source),
        ]);
    }
}
