import { useNuxtApp } from '#app'

/**
 * Composable for handling API errors, especially for organization-related errors
 */
export const useAp2iErrorHandler = () => {
  const { $i18n } = useNuxtApp()

  /**
   * Process API error and extract meaningful error message
   * @param error - The error object from API response
   * @returns Processed error message
   */
  const processApiError = (error: unknown): string => {
    let errorMessage =
      "Une erreur s'est produite. Veuillez réessayer plus tard ou nous contacter directement."

    // Try to extract the specific error message from the API response
    if (
      error &&
      typeof error === 'object' &&
      'data' in error &&
      error.data &&
      typeof error.data === 'object'
    ) {
      const errorData = error.data as { detail?: string }
      if (errorData.detail) {
        // Check if it's the specific error about organization already existing
        const organizationExistsRegex =
          /Handling ".*" failed: An organization named '(.+)' already exists in (.+)/
        const match = errorData.detail.match(organizationExistsRegex)

        if (match) {
          // Extract the organization name and city name and use the translation
          const organizationName = match[1]
          const cityName = match[2]
          const translationKey =
            "An organization named '%s' already exists in %s"

          const translatedMessage = $i18n.t(translationKey, [
            organizationName,
            cityName,
          ])
          errorMessage = translatedMessage as string
        } else {
          // For other errors, use translation if available, otherwise use the original message
          if (!errorData.detail) return errorData.detail

          // Remove the "Handling ... failed:" part if present
          let cleanedDetail = errorData.detail
          const handlingFailedRegex = /Handling ".*" failed: (.*)/
          const handlingMatch = cleanedDetail.match(handlingFailedRegex)

          if (handlingMatch) {
            cleanedDetail = handlingMatch[1]
          }

          errorMessage = ($i18n.t(cleanedDetail) || cleanedDetail) as string
        }
      }
    }

    return errorMessage
  }

  return {
    processApiError,
  }
}
