<?php

declare(strict_types=1);

namespace FleekDash\Services;

/**
 * Update Counters Service
 *
 * Provides a single source of truth for WordPress update counts.
 * Uses WordPress core functions to calculate total pending updates
 * (core, plugins, and themes).
 *
 * @package FleekDash\Services
 */
class UpdateCountersService
{
    /**
     * Get total update count (core + plugins + themes)
     *
     * Uses wp_get_update_data() which is the WordPress standard function
     * for retrieving update counts. This ensures consistency with WordPress
     * core behavior and includes all update types.
     *
     * @return int Total number of pending updates
     */
    public static function getTotalUpdateCount(): int
    {
        // Do NOT call wp_clean_update_cache() here!
        // wp_clean_update_cache() DELETES the update transients, causing wp_get_update_data()
        // to return 0 in REST context where updates can't be rechecked.
        // Instead, trust the existing transient data that WordPress maintains via cron.

        // Use WordPress standard function for update counts
        $updates = \wp_get_update_data();

        if (isset($updates['counts']) && isset($updates['counts']['total'])) {
            return (int) $updates['counts']['total'];
        }

        // Fallback: return 0 if update data is not available
        return 0;
    }

    /**
     * Get detailed update counts by type
     *
     * Returns an array with counts for core, plugins, and themes separately.
     *
     * @return array{
     *   total: int,
     *   core: int,
     *   plugins: int,
     *   themes: int
     * }
     */
    public static function getDetailedUpdateCounts(): array
    {
        // Do NOT call wp_clean_update_cache() here!
        // It deletes the update transients, causing wp_get_update_data() to return 0.

        $updates = \wp_get_update_data();
        $counts = $updates['counts'] ?? [];

        return [
            'total' => (int) ($counts['total'] ?? 0),
            'core' => (int) ($counts['wordpress'] ?? 0),
            'plugins' => (int) ($counts['plugins'] ?? 0),
            'themes' => (int) ($counts['themes'] ?? 0),
        ];
    }
}
