/**
 * Connection Validation Types
 *
 * Types and utilities for validating API provider connections.
 * Provides detailed error messages and suggested actions for common failure scenarios.
 */

/**
 * Provider settings interface (legacy, used by LLMService/ChatService)
 */
export interface ProviderSettings {
  apiKey: string;
  baseUrl: string;
  modelName: string;
}

/**
 * A saved provider profile with all credentials
 */
export interface ProviderProfile {
  /** Unique identifier for this profile */
  id: string;
  /** User-defined label for this provider (e.g., "Work OpenAI", "Personal DeepSeek") */
  name: string;
  /** API base URL */
  baseUrl: string;
  /** API key (encoded in storage, decoded in memory) */
  apiKey: string;
  /** Model name to use */
  modelName: string;
  /** When this profile was created */
  createdAt: string;
  /** When this profile was last updated */
  updatedAt: string;
}

/**
 * Collection of saved provider profiles
 */
export interface SavedProviders {
  /** All saved provider profiles */
  profiles: ProviderProfile[];
  /** ID of the currently active provider */
  activeProviderId: string | null;
}

/**
 * Migration state for legacy single-provider format
 */
export interface ProviderMigrationState {
  /** Whether migration has been completed */
  hasMigrated: boolean;
  /** When migration occurred */
  migratedAt?: string;
}

/**
 * Result of a connection validation attempt
 */
export interface ConnectionValidationResult {
  /** Whether the connection is valid */
  isValid: boolean;
  /** Type of error if validation failed */
  errorType?: ApiErrorType;
  /** User-friendly error message */
  errorMessage?: string;
  /** Suggested action to fix the error */
  suggestedAction?: string;
  /** Raw error response for debugging */
  rawError?: unknown;
}

/**
 * Categories of API errors that can occur during validation
 */
export enum ApiErrorType {
  /** API key is invalid or expired */
  INVALID_KEY = 'INVALID_KEY',
  /** Base URL is malformed or unreachable */
  INVALID_URL = 'INVALID_URL',
  /** API quota/limit exceeded */
  QUOTA_EXCEEDED = 'QUOTA_EXCEEDED',
  /** Network connectivity issue */
  NETWORK_ERROR = 'NETWORK_ERROR',
  /** Model name not found */
  MODEL_NOT_FOUND = 'MODEL_NOT_FOUND',
  /** Unknown error */
  UNKNOWN = 'UNKNOWN',
}

/**
 * User-friendly error messages and suggested actions for each error type
 */
export const ERROR_MESSAGES: Record<ApiErrorType, { message: string; action: string }> = {
  [ApiErrorType.INVALID_KEY]: {
    message: 'Your API key appears to be invalid or expired.',
    action: 'Please check your API key in your provider dashboard and try again.',
  },
  [ApiErrorType.INVALID_URL]: {
    message: 'The API URL is not reachable.',
    action: 'Please verify the Base URL matches your provider\'s API endpoint format.',
  },
  [ApiErrorType.QUOTA_EXCEEDED]: {
    message: 'Your API quota has been exceeded.',
    action: 'Please check your billing status or upgrade your plan.',
  },
  [ApiErrorType.MODEL_NOT_FOUND]: {
    message: 'The specified model was not found.',
    action: 'Please check the model name for typos or verify it exists in your account.',
  },
  [ApiErrorType.NETWORK_ERROR]: {
    message: 'Unable to reach the API server.',
    action: 'Please check your internet connection and try again.',
  },
  [ApiErrorType.UNKNOWN]: {
    message: 'An unexpected error occurred.',
    action: 'Please try again or contact support if the issue persists.',
  },
};

/**
 * Creates a successful validation result
 */
export function createValidationSuccess(): ConnectionValidationResult {
  return { isValid: true };
}

/**
 * Creates a validation error result
 */
export function createValidationError(
  errorType: ApiErrorType,
  rawError?: unknown
): ConnectionValidationResult {
  const errorInfo = ERROR_MESSAGES[errorType];
  return {
    isValid: false,
    errorType,
    errorMessage: errorInfo.message,
    suggestedAction: errorInfo.action,
    rawError,
  };
}
