<?php
declare(strict_types=1);

namespace Ekesto\CacheInvalidator\Integrations\Caching\Adapters;

use Ekesto\CacheInvalidator\Integrations\Caching\CacheAdapterInterface;

/**
 * WP Super Cache adapter.
 *
 * Uses the WP Super Cache API function wp_cache_post_change() to purge a post/page.
 */
final class WpSuperCacheAdapter implements CacheAdapterInterface
{
    /**
     * @inheritDoc
     */
    public function getLabel(): string
    {
        return 'WP Super Cache';
    }

    /**
     * @inheritDoc
     */
    public function getKey(): string
    {
        return 'wp-super-cache';
    }

    /**
     * @inheritDoc
     */
    public function isAvailable(): bool
    {
        return function_exists('wp_cache_post_change');
    }

    /**
     * @inheritDoc
     */
    public function supportsCacheStatusDetection(): bool
    {
        return false;
    }

    /**
     * @inheritDoc
     */
    public function isCacheEnabled(): bool
    {
        return true;
    }

    /**
     * @inheritDoc
     */
    public function registerHooks(): void
    {
        // No-op for now.
    }

    /**
     * @inheritDoc
     */
    public function purgePostId(int $postId): bool
    {
        $postId = absint($postId);
        if ($postId <= 0) {
            return false;
        }

        if (!$this->isAvailable()) {
            return false;
        }

        wp_cache_post_change($postId);

        return true;
    }

    /**
     * Clears all cache entries.
     *
     * @return bool True if a supported purge-all call was executed.
     */
    public function purgeAll(): bool
    {
        if (!function_exists('wp_cache_clear_cache')) {
            return false;
        }

        $blogId = function_exists('get_current_blog_id') ? absint(get_current_blog_id()) : 0;

        // WP Super Cache expects multisite-only APIs when a non-zero blog ID is provided.
        if ($blogId > 0 && function_exists('get_blog_option')) {
            wp_cache_clear_cache($blogId);
            return true;
        }

        wp_cache_clear_cache();
        return true;
    }
}
