<?php
declare(strict_types=1);

namespace Ekesto\CacheInvalidator\Integrations\Caching\Adapters;

use Ekesto\CacheInvalidator\Integrations\Caching\CacheAdapterInterface;
use Ekesto\CacheInvalidator\Integrations\Caching\UrlPurgeCapableAdapterInterface;

/**
 * W3 Total Cache adapter.
 *
 * Uses W3TC API functions to purge by post ID, URL, or entire cache.
 */
final class W3TotalCacheAdapter implements CacheAdapterInterface, UrlPurgeCapableAdapterInterface
{
    /**
     * Returns a human-readable adapter label.
     *
     * @return string
     */
    public function getLabel(): string
    {
        return 'W3 Total Cache';
    }

    /**
     * Returns a unique adapter key.
     *
     * @return string
     */
    public function getKey(): string
    {
        return 'w3-total-cache';
    }

    /**
     * Returns whether W3TC purge APIs are available.
     *
     * @return bool
     */
    public function isAvailable(): bool
    {
        return function_exists('w3tc_flush_post')
            && function_exists('w3tc_flush_all');
    }

    /**
     * Returns whether W3 Total Cache supports runtime cache-status detection.
     *
     * @return bool
     */
    public function supportsCacheStatusDetection(): bool
    {
        return false;
    }

    /**
     * Returns whether W3 Total Cache should be treated as enabled.
     *
     * @return bool
     */
    public function isCacheEnabled(): bool
    {
        return true;
    }

    /**
     * Registers adapter-specific hooks.
     *
     * @return void
     */
    public function registerHooks(): void
    {
        // No-op. Purge APIs are invoked directly.
    }

    /**
     * Purges cache for a specific post ID.
     *
     * @param int $postId Post/page ID to purge.
     * @return bool True when purge call was executed.
     */
    public function purgePostId(int $postId): bool
    {
        $postId = absint($postId);
        if ($postId <= 0) {
            return false;
        }

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

        w3tc_flush_post($postId);

        return true;
    }

    /**
     * Purges cache for a specific absolute URL.
     *
     * @param string $url Absolute URL.
     * @return bool True when purge call was executed.
     */
    public function purgeUrl(string $url): bool
    {
        $url = trim($url);
        if ($url === '') {
            return false;
        }

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

        if (!function_exists('w3tc_flush_url')) {
            return false;
        }

        w3tc_flush_url($url);

        return true;
    }

    /**
     * Purges all cache entries for the active site.
     *
     * @return bool True when purge call was executed.
     */
    public function purgeAll(): bool
    {
        if (!$this->isAvailable()) {
            return false;
        }

        w3tc_flush_all();

        return true;
    }
}
