<?php
declare(strict_types=1);

namespace Ekesto\CacheWarmup\Core;

/**
 * Central trigger_key label lookup for system-event run labels.
 */
final class TriggerKeyLabelMap
{
    /**
     * Exact trigger key label map.
     *
     * @var array<string,string>
     */
    private const EXACT = [
        'cache_plugin_cleared' => 'Cache plugin cleared',
        'widgets_change' => 'Widget change',
        'manual_settings_general' => 'Manual cache refresh',
        'manual_admin_bar' => 'Manual cache refresh',
        // @deprecated Legacy alias from sanitize_key()-stripped manual trigger_event values.
        // @remove-after 6.0.0
        'manualsettings_general' => 'Manual cache refresh',
        // @deprecated Legacy alias from sanitize_key()-stripped manual trigger_event values.
        // @remove-after 6.0.0
        'manualadmin_bar' => 'Manual cache refresh',
        'maintenance:plugin_activated' => 'Plugin activated',
        'maintenance:plugin_deactivated' => 'Plugin deactivated',
        'maintenance:theme_switched' => 'Theme switched',
    ];

    /**
     * Prefix trigger key label map.
     *
     * Intentional broad grouping: all upgrade:* keys map to one label.
     *
     * @var array<string,string>
     */
    private const PREFIX = [
        'upgrade:' => 'System update',
    ];

    /**
     * Resolve a human-readable label for a trigger key.
     *
     * Matching order:
     * 1) Exact match
     * 2) Prefix match
     * 3) Null when no mapping exists
     *
     * @param string $triggerKey Canonical trigger key.
     * @return string|null
     */
    public static function get(string $triggerKey): ?string
    {
        $triggerKey = strtolower(trim($triggerKey));
        if ($triggerKey === '') {
            return null;
        }

        if (isset(self::EXACT[$triggerKey])) {
            return self::EXACT[$triggerKey];
        }

        foreach (self::PREFIX as $matchPrefix => $label) {
            if (str_starts_with($triggerKey, $matchPrefix)) {
                return $label;
            }
        }

        return null;
    }
}
