import { AxiosError } from 'axios'
import { toast } from 'sonner'

export function handleServerError(error: unknown) {
  // eslint-disable-next-line no-console
  console.log(error)

  let errMsg = 'Something went wrong!'

  if (
    error &&
    typeof error === 'object' &&
    'status' in error &&
    Number(error.status) === 204
  ) {
    errMsg = 'Content not found.'
  }

  if (error instanceof AxiosError) {
    if (error.response?.status === 429) {
      toast.error('Çok fazla istek gönderildi. Lütfen biraz bekleyin.')
      return
    }

    const responseData = error.response?.data as
      | {
          message?: string
          title?: string
          errors?: Record<string, string[] | string>
        }
      | undefined

    const fieldErrors = responseData?.errors
      ? Object.values(responseData.errors)
          .flatMap((value) => (Array.isArray(value) ? value : [value]))
          .filter(Boolean)
      : []

    errMsg =
      fieldErrors[0] ??
      responseData?.message ??
      responseData?.title ??
      error.message ??
      errMsg
  }

  toast.error(errMsg)
}
