import axios from 'axios'

type ApiErrorBody = {
  message?: string
  errors?: Record<string, string[]>
}

export function getApiValidationErrors(error: unknown): Record<string, string[]> | null {
  if (axios.isAxiosError(error)) {
    const data = error.response?.data as ApiErrorBody | undefined

    if (data?.errors && Object.keys(data.errors).length > 0) {
      return data.errors
    }
  }

  return null
}

export function getApiErrorMessage(
  error: unknown,
  fallback = 'Something went wrong. Please try again.',
): string {
  if (axios.isAxiosError(error)) {
    const data = error.response?.data as ApiErrorBody | undefined

    if (data?.errors) {
      const firstError = Object.values(data.errors).flat()[0]
      if (firstError) return firstError
    }

    if (data?.message) return data.message

    if (error.message) return error.message
  }

  if (error instanceof Error) {
    return error.message
  }

  return fallback
}
