/**
 * Unified Error Message System
 * 统一错误信息系统 - 高内聚、精准表达、分层清晰
 * 
 * 分层结构:
 * - Network: 网络连接层错误
 * - Resource: 资源操作错误 (CRUD)
 * - Validation: 数据验证错误
 * - Business: 业务逻辑错误
 */

// ============================================
// Network Layer Errors
// ============================================
export const NetworkErrors = {
  CONNECTION_FAILED: "Network connection failed. Please check your internet connection.",
  TIMEOUT: "Request timeout. The server took too long to respond.",
  UNAUTHORIZED: "Authentication required. Please log in again.",
  FORBIDDEN: "Access denied. You don't have permission to perform this action.",
  NOT_FOUND: "Resource not found. The requested item may have been deleted.",
  SERVER_ERROR: "Internal server error. Please try again later.",
  SERVICE_UNAVAILABLE: "Service temporarily unavailable. Please try again later.",
} as const;

// ============================================
// Resource Operation Errors (CRUD)
// ============================================

/** Cluster Resource Errors */
export const ClusterErrors = {
  LOAD_FAILED: "Failed to load clusters. Please refresh the page.",
  CREATE_FAILED: "Failed to create cluster. Please check your configuration.",
  UPDATE_FAILED: "Failed to update cluster. Please verify the changes.",
  DELETE_FAILED: "Failed to delete cluster. This cluster may be in use.",
  CONNECTION_FAILED: "Failed to connect to cluster. Please verify the connection details.",
  NOT_FOUND: "Cluster not found. It may have been removed.",
} as const;

/** Registry Resource Errors */
export const RegistryErrors = {
  LOAD_FAILED: "Failed to load registries. Please refresh the page.",
  CREATE_FAILED: "Failed to create registry. Please check your configuration.",
  UPDATE_FAILED: "Failed to update registry. Please verify the changes.",
  DELETE_FAILED: "Failed to delete registry. This registry may be in use.",
  CONNECTION_TEST_FAILED: "Failed to connect to registry. Please verify the URL and credentials.",
  NOT_FOUND: "Registry not found. It may have been removed.",
  REPOSITORIES_LOAD_FAILED: "Failed to load repositories. Please check registry connection.",
  TAGS_LOAD_FAILED: "Failed to load tags. Please check repository access.",
} as const;

/** Instance Resource Errors */
export const InstanceErrors = {
  LOAD_FAILED: "Failed to load instances. Please refresh the page.",
  DEPLOY_FAILED: "Failed to deploy instance. Please check your configuration.",
  UPDATE_FAILED: "Failed to update instance. Please verify the changes.",
  DELETE_FAILED: "Failed to delete instance. The instance may still be running.",
  STATUS_FETCH_FAILED: "Failed to fetch instance status. Please try again.",
  HISTORY_LOAD_FAILED: "Failed to load deployment history.",
  ROLLBACK_FAILED: "Failed to rollback instance. Please check the target revision.",
  UPGRADE_FAILED: "Failed to upgrade instance. Please verify the new version.",
} as const;

// ============================================
// Validation Errors
// ============================================
export const ValidationErrors = {
  REQUIRED_FIELD: (field: string) => `${field} is required.`,
  INVALID_FORMAT: (field: string) => `Invalid ${field} format.`,
  INVALID_URL: "Invalid URL format. Please enter a valid URL.",
  INVALID_PORT: "Invalid port number. Must be between 1 and 65535.",
  EMPTY_VALUE: (field: string) => `${field} cannot be empty.`,
  MIN_LENGTH: (field: string, min: number) => `${field} must be at least ${min} characters.`,
  MAX_LENGTH: (field: string, max: number) => `${field} cannot exceed ${max} characters.`,
} as const;

// ============================================
// Business Logic Errors
// ============================================
export const BusinessErrors = {
  DUPLICATE_NAME: (resource: string) => `${resource} with this name already exists.`,
  RESOURCE_IN_USE: (resource: string) => `Cannot delete ${resource} because it is currently in use.`,
  INSUFFICIENT_RESOURCES: "Insufficient cluster resources to deploy this instance.",
  INCOMPATIBLE_VERSION: "This version is incompatible with the current deployment.",
  OPERATION_CONFLICT: "Another operation is in progress. Please wait and try again.",
} as const;

// ============================================
// Success Messages
// ============================================
export const SuccessMessages = {
  // Cluster
  CLUSTER_CREATED: "Cluster created successfully.",
  CLUSTER_UPDATED: "Cluster updated successfully.",
  CLUSTER_DELETED: "Cluster deleted successfully.",
  
  // Registry
  REGISTRY_CREATED: "Registry created successfully.",
  REGISTRY_UPDATED: "Registry updated successfully.",
  REGISTRY_DELETED: "Registry deleted successfully.",
  REGISTRY_CONNECTION_OK: "Registry connection successful.",
  
  // Instance
  INSTANCE_DEPLOYED: "Instance deployed successfully.",
  INSTANCE_UPDATED: "Instance updated successfully.",
  INSTANCE_DELETED: "Instance deleted successfully.",
  INSTANCE_UPGRADED: "Instance upgraded successfully.",
  INSTANCE_ROLLED_BACK: "Instance rolled back successfully.",
  INSTANCE_STATUS_REFRESHED: "Instance status refreshed.",
  
  // Generic
  DATA_REFRESHED: "Data refreshed successfully.",
  OPERATION_COMPLETED: "Operation completed successfully.",
} as const;

// ============================================
// Utility Functions
// ============================================

/**
 * Format error message from API response
 * 从 API 响应中格式化错误消息
 * 
 * 分层处理优先级:
 * 1. Network Layer: 检查网络连接错误 (ERR_NETWORK, ECONNREFUSED, timeout)
 * 2. HTTP Status: 根据状态码返回标准错误 (401, 403, 404, 500, 503)
 * 3. API Response: 提取后端返回的具体错误消息
 * 4. Generic: 通用错误兜底
 */
export function formatApiError(error: any): string | null {
  // Layer 1: Network Connection Errors (最高优先级)
  // 检查是否是网络连接问题
  if (error?.code === 'ERR_NETWORK' || error?.code === 'ECONNREFUSED' || error?.code === 'ECONNABORTED') {
    return NetworkErrors.CONNECTION_FAILED;
  }
  
  if (error?.message?.toLowerCase().includes('network')) {
    return NetworkErrors.CONNECTION_FAILED;
  }
  
  if (error?.message?.toLowerCase().includes('timeout')) {
    return NetworkErrors.TIMEOUT;
  }
  
  // Layer 2: HTTP Status Codes (标准HTTP错误)
  const status = error?.response?.status;
  const apiMessage = error?.response?.data?.message;
  const apiError = error?.response?.data?.error;
  if ((status === 400 || status === 403 || status === 422) && apiMessage) {
    return apiMessage;
  }
  if ((status === 400 || status === 403 || status === 422) && apiError) {
    return apiError;
  }
  if (status) {
    switch (status) {
      case 401:
        return NetworkErrors.UNAUTHORIZED;
      case 403:
        return NetworkErrors.FORBIDDEN;
      case 404:
        return NetworkErrors.NOT_FOUND;
      case 408:
        return NetworkErrors.TIMEOUT;
      case 500:
        return NetworkErrors.SERVER_ERROR;
      case 503:
        return NetworkErrors.SERVICE_UNAVAILABLE;
    }
  }
  
  // Layer 3: API Response Messages (后端返回的具体错误)
  // 提取后端返回的详细错误信息
  if (apiMessage) {
    return apiMessage;
  }
  
  if (apiError) {
    return apiError;
  }
  
  // Layer 4: Generic Error Messages
  if (typeof error === 'string') {
    return error;
  }
  
  if (error?.message) {
    return error.message;
  }
  
  // 返回 null 表示无法格式化，调用方应使用默认错误消息
  return null;
}

/**
 * Get error message based on HTTP status code
 * 根据 HTTP 状态码获取错误消息
 */
export function getErrorByStatus(status: number, defaultMessage: string): string {
  switch (status) {
    case 401:
      return NetworkErrors.UNAUTHORIZED;
    case 403:
      return NetworkErrors.FORBIDDEN;
    case 404:
      return NetworkErrors.NOT_FOUND;
    case 408:
      return NetworkErrors.TIMEOUT;
    case 500:
      return NetworkErrors.SERVER_ERROR;
    case 503:
      return NetworkErrors.SERVICE_UNAVAILABLE;
    default:
      return defaultMessage;
  }
}

/**
 * Create resource operation error handler
 * 创建资源操作错误处理器
 */
export function createErrorHandler(
  resourceErrors: Record<string, string>,
  operation: keyof typeof resourceErrors
) {
  return (error: any): string => {
    const status = error?.response?.status;
    if (status) {
      const statusError = getErrorByStatus(status, resourceErrors[operation]);
      if (statusError !== resourceErrors[operation]) {
        return statusError;
      }
    }
    
    const apiError = formatApiError(error);
    if (apiError) {
      return apiError;
    }
    
    return resourceErrors[operation];
  };
}

/**
 * Type-safe error message getter
 * 类型安全的错误消息获取器
 */
export type ErrorMessages = 
  | typeof NetworkErrors
  | typeof ClusterErrors
  | typeof RegistryErrors
  | typeof InstanceErrors
  | typeof ValidationErrors
  | typeof BusinessErrors;
