<?php

namespace FleekDash\Core;

use WP_REST_Request;
use WP_REST_Response;

/**
 * Handles debug-related cache operations (REST cache info, ETags, clear-all).
 * Extracted from DebugController for S1448 compliance (method count).
 */
class DebugCacheHandler
{
    private const OPTION_NAME_LIKE = 'option_name LIKE %s';

    /**
     * Return current REST cache configuration (patterns and default max-age)
     *
     * @param WP_REST_Request|null $request
     * @return WP_REST_Response
     */
    public function getRestCacheInfo(?WP_REST_Request $request = null)
    {
        try {
            $patterns = [
                '/wp/v2/posts',
                '/wp/v2/pages',
                '/wp/v2/comments',
                '/wp/v2/media',
                '/wp/v2/categories',
                '/wp/v2/tags',
                'fleekdash/v1',
            ];
            if (function_exists('apply_filters')) {
                $patterns = \apply_filters('fleekdash_cacheable_rest_patterns', $patterns, $request);
            }

            $default_max_age = 120;
            if (function_exists('apply_filters')) {
                $default_max_age = (int) \apply_filters('fleekdash_rest_cache_max_age', $default_max_age, null, '');
            }

            return new WP_REST_Response([
                'success' => true,
                'data' => [
                    'patterns' => array_values(array_unique($patterns)),
                    'default_max_age' => max(0, (int) $default_max_age),
                ],
            ], 200);
        } catch (\Throwable $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to retrieve rest cache info: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Clear all stored ETag transients for fleekdash endpoints
     *
     * @return WP_REST_Response
     */
    public function clearEtags()
    {
        global $wpdb;
        try {
            $like_keys = [
                '_transient_fleekdash_etag_%',
                '_transient_timeout_fleekdash_etag_%',
            ];

            $placeholders = implode(' OR ', array_fill(0, count($like_keys), self::OPTION_NAME_LIKE));
            $sql = "SELECT option_name FROM {$wpdb->options} WHERE {$placeholders}";
            $prepared = $wpdb->prepare($sql, $like_keys); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
            $rows = $wpdb->get_col($prepared);

            $deleted = 0;
            if (!empty($rows)) {
                foreach ($rows as $option_name) {
                    if (\delete_option($option_name)) {
                        $deleted++;
                    }
                }
            }

            return new WP_REST_Response([
                'success' => true,
                'message' => 'Cleared ETag transients',
                'data' => [
                    'deleted' => (int) $deleted,
                    'matched' => (int) count($rows),
                ],
            ], 200);
        } catch (\Throwable $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to clear ETag transients: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Clear All Cache - ETags, FleekDash transients, REST cache
     *
     * @return WP_REST_Response
     */
    public function clearAllCache()
    {
        global $wpdb;
        try {
            $results = [
                'etags_deleted' => 0,
                'transients_deleted' => 0,
                'rest_cache_cleared' => false,
            ];

            $etag_keys = [
                '_transient_fleekdash_etag_%',
                '_transient_timeout_fleekdash_etag_%',
            ];
            $placeholders = implode(' OR ', array_fill(0, count($etag_keys), self::OPTION_NAME_LIKE));
            $sql = "SELECT option_name FROM {$wpdb->options} WHERE {$placeholders}";
            $prepared = $wpdb->prepare($sql, $etag_keys); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
            $etag_rows = $wpdb->get_col($prepared);

            foreach ($etag_rows as $option_name) {
                if (\delete_option($option_name)) {
                    $results['etags_deleted']++;
                }
            }

            $transient_keys = [
                '_transient_fleekdash_%',
                '_transient_timeout_fleekdash_%',
            ];
            $placeholders = implode(' OR ', array_fill(0, count($transient_keys), 'option_name LIKE %s'));
            $sql = "SELECT option_name FROM {$wpdb->options} WHERE {$placeholders}";
            $prepared = $wpdb->prepare($sql, $transient_keys); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
            $transient_rows = $wpdb->get_col($prepared);

            foreach ($transient_rows as $option_name) {
                if (strpos($option_name, 'fleekdash_etag_') === false && \delete_option($option_name)) {
                    $results['transients_deleted']++;
                }
            }

            if (function_exists('wp_cache_flush')) {
                wp_cache_flush();
                $results['rest_cache_cleared'] = true;
            }

            if (function_exists('fleekdash_log_info')) {
                fleekdash_log_info('FleekDash Debug: All cache cleared by user ID ' . \get_current_user_id() .
                    ' - ETags: ' . $results['etags_deleted'] .
                    ', Transients: ' . $results['transients_deleted']);
            }

            return new WP_REST_Response([
                'success' => true,
                'message' => 'All cache cleared successfully',
                'data' => $results,
            ], 200);
        } catch (\Throwable $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error clearing all cache - ' . $e->getMessage());
            }
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to clear all cache: ' . $e->getMessage(),
            ], 500);
        }
    }
}
