import type { AxiosError } from 'axios'

import type { IBaseResponse } from '@/@core/types/api'

export type ApiResponse<T = any> = IBaseResponse<T> & { message?: string }

const resolveApiMessage = (payload?: ApiResponse<any>) => {
  if (!payload) return undefined

  if (payload.message) {
    return payload.message
  }

  if (Array.isArray(payload.messages) && payload.messages.length > 0) {
    const [first] = payload.messages
    return typeof first === 'string' ? first : undefined
  }

  if (typeof payload.messages === 'string') {
    return payload.messages
  }

  return undefined
}

export const getSuccessMessage = <T>(payload: ApiResponse<T> | undefined, fallback: string) =>
  resolveApiMessage(payload) ?? fallback

export const getErrorMessage = (error: unknown, fallback: string) => {
  const axiosError = error as AxiosError<ApiResponse>

  return resolveApiMessage(axiosError?.response?.data) ?? fallback
}
