import type { AxiosError } from 'axios'

/**
 * Maps technical error responses to user-friendly messages in Bahasa Indonesia
 * for non-tech-savvy users (ibu-ibu awam)
 */
export function mapErrorToUserMessage(error: unknown): string {
  // Handle AxiosError
  if (error && typeof error === 'object' && 'response' in error) {
    const axiosError = error as AxiosError
    const status = axiosError.response?.status

    // HTTP 409 - Conflict (VA/QR/Code already created)
    if (status === 409) {
      return 'Kode pembayaran Anda sudah dibuat! Silakan gunakan kode yang sudah ada.'
    }

    // HTTP 404 - Not Found
    if (status === 404) {
      return 'Terjadi kesalahan. Silakan coba lagi.'
    }

    // HTTP 500 - Internal Server Error
    if (status === 500) {
      return 'Terjadi kesalahan server. Silakan coba lagi nanti.'
    }

    // HTTP 503 - Service Unavailable
    if (status === 503) {
      return 'Layanan sedang sibuk. Silakan coba lagi dalam beberapa saat.'
    }

    // Network error (no response)
    if (axiosError.message === 'Network Error' || !axiosError.response) {
      return 'Tidak dapat terhubung ke server. Periksa koneksi internet Anda.'
    }

    // Try to get message from response data
    const responseMessage = (axiosError.response?.data as any)?.message
    if (typeof responseMessage === 'string' && responseMessage.length > 0) {
      // If it's already in Indonesian, use it
      if (/[a-zA-Z]/.test(responseMessage) === false) {
        return responseMessage
      }
    }
  }

  // Handle Error object
  if (error instanceof Error) {
    // Network errors
    if (error.message.includes('Network') || error.message.includes('network')) {
      return 'Tidak dapat terhubung ke server. Periksa koneksi internet Anda.'
    }

    // Timeout errors
    if (error.message.includes('timeout') || error.message.includes('Timeout')) {
      return 'Permintaan memakan waktu terlalu lama. Silakan coba lagi.'
    }
  }

  // Default fallback message
  return 'Terjadi kesalahan. Silakan coba lagi.'
}

/**
 * Gets recovery action suggestion based on error type
 */
export function getErrorRecoveryAction(error: unknown): 'retry' | 'view-existing' | 'back' {
  if (error && typeof error === 'object' && 'response' in error) {
    const axiosError = error as AxiosError
    const status = axiosError.response?.status

    // HTTP 409 - Conflict (already exists) → view existing
    if (status === 409) {
      return 'view-existing'
    }
  }

  // Default: allow retry
  return 'retry'
}
