import i18n from "i18next"

import type { TxKeyPath } from "@/i18n"

// Error code pattern: E001, E011, E021, etc.
const ERROR_CODE_PATTERN = /^E\d{3}$/

// Map API problem kinds to i18n keys
const PROBLEM_KIND_MAP: Record<string, TxKeyPath> = {
  "timeout": "authErrors:timeout",
  "cannot-connect": "authErrors:cannotConnect",
  "server": "authErrors:serverError",
  "bad-data": "authErrors:badData",
  "unauthorized": "authErrors:E011", // Default to invalid credentials
  "forbidden": "authErrors:E024", // Default to account disabled
  "not-found": "authErrors:E028", // Default to user not found
  "rejected": "authErrors:unknownError",
  "unknown": "authErrors:unknownError",
}

/**
 * Translates an API error response to a localized error message.
 *
 * @param errorCode - The error code from the API response (e.g., "E011")
 * @param message - The fallback message if no translation is found
 * @param problemKind - The API problem kind (e.g., "timeout", "cannot-connect")
 * @returns The translated error message
 */
export function translateAuthError(
  errorCode?: string,
  message?: string,
  problemKind?: string,
): string {
  // 1. Try to translate by error code (e.g., E001, E011)
  if (errorCode && ERROR_CODE_PATTERN.test(errorCode)) {
    const key = `authErrors:${errorCode}` as TxKeyPath
    const translated = i18n.t(key)
    // If translation exists (not returning the key itself), use it
    if (translated && translated !== key && !translated.startsWith("authErrors:")) {
      return translated
    }
  }

  // 2. Try to translate by problem kind (e.g., timeout, cannot-connect)
  if (problemKind && PROBLEM_KIND_MAP[problemKind]) {
    return i18n.t(PROBLEM_KIND_MAP[problemKind])
  }

  // 3. Return the original message or a default error
  return message || i18n.t("authErrors:unknownError")
}

/**
 * Gets the i18n key for an error code.
 * Useful for displaying error messages with the Text component's tx prop.
 *
 * @param errorCode - The error code from the API response
 * @returns The i18n key path or undefined if not found
 */
export function getAuthErrorKey(errorCode?: string): TxKeyPath | undefined {
  if (errorCode && ERROR_CODE_PATTERN.test(errorCode)) {
    return `authErrors:${errorCode}` as TxKeyPath
  }
  return undefined
}

/**
 * Checks if an error code is a known auth error.
 *
 * @param errorCode - The error code to check
 * @returns True if the error code is a known auth error
 */
export function isKnownAuthError(errorCode?: string): boolean {
  if (!errorCode || !ERROR_CODE_PATTERN.test(errorCode)) {
    return false
  }

  const key = `authErrors:${errorCode}` as TxKeyPath
  const translated = i18n.t(key)
  return translated !== key && !translated.startsWith("authErrors:")
}
