// Filename: frontend/js/services/errorHandler.js

/**
 * This module provides a centralized place for handling application-wide errors,
 * particularly those originating from API calls. It promotes a consistent user
 * experience for error notifications.
 */

// Step 1: Define the single, authoritative map for all client-side error messages.
// This is the "dictionary" that translates API error codes into user-friendly text.
export const ERROR_MESSAGES = {
    'STATE_CONFLICT_MASTER_REVOKED': '操作失败：无法激活一个已被永久吊销（Revoked）的Key。',
    'NOT_FOUND': '操作失败：目标资源不存在或已从本组移除。列表将自动刷新。',
    'NO_KEYS_MATCH_FILTER': '没有找到任何符合当前过滤条件的Key可供操作。',
    // You can add many more specific codes here as your application grows.
    
    'DEFAULT': '操作失败，请稍后重试或联系管理员。'
};

/**
 * A universal API error handler function.
 * It inspects an error object, determines the best message to show,
 * and displays it using the provided toastManager.
 *
 * @param {Error|APIClientError} error - The error object caught in a try...catch block.
 * @param {object} toastManager - The toastManager instance to display notifications.
 * @param {object} [options={}] - Optional parameters for customization.
 * @param {string} [options.prefix=''] - A string to prepend to the error message (e.g., "任务启动失败: ").
 */
export function handleApiError(error, toastManager, options = {}) {
    const prefix = options.prefix || '';
    
    // Use the exact same robust logic we developed before.
    const errorCode = error?.code || 'DEFAULT';
    const displayMessage = ERROR_MESSAGES[errorCode] || error.rawMessageFromServer || error.message || ERROR_MESSAGES['DEFAULT'];

    toastManager.show(`${prefix}${displayMessage}`, 'error');
}

