/* eslint-disable @typescript-eslint/no-explicit-any */
import axios from 'axios'
import { getFormDataHeader, getHeaderInfo } from '@/rtk/helpers/tokenCreator'
import { removeTokens } from '@/rtk/localStorage'
import { notifications } from '@mantine/notifications'
const handleResponse = (response: any) => {
  if (response.status === 401) {
    removeTokens()
    window.location.href = '/login'
  }
  if (response.data.status !== 'OK') {
    return response.data
  }
  return response
}

/**
 *
 * @param url
 * @param body
 * @param otherHeader options
 * @returns
 */
export const post = async (url: string, body: any, otherHeader?: any) => {
  const header = await getHeaderInfo()
  try {
    if (otherHeader) {
      const resp = await axios.post(url, body, otherHeader)
      return handleResponse(resp)
    } else {
      const resp = await axios.post(url, body, header)
      return handleResponse(resp)
    }
  } catch (err: any) {
    if (err.response.status === 422) {
      const errorMess = err.response.data.message
      notifications.show({
        title: 'Error',
        message: errorMess,
        color: 'red',
      })
    }
    return handleResponse(err.response)
  }
}

/**
 *
 * @param url
 * @param params
 * @returns
 */
export const get = async (url: any, params: any = {}) => {
  const header = await getHeaderInfo()
  try {
    const resp = await axios.get(url, { ...header, params })
    return handleResponse(resp)
  } catch (err: any) {
    console.log(err)
    if (err.response.status === 422) {
      const errorMess = err.response.data.message
      notifications.show({
        title: 'Error',
        message: errorMess,
        color: 'red',
      })
    }
    throw handleResponse(err.response)
  }
}

export const put = async (url: any, body: any) => {
  const header = await getHeaderInfo()

  try {
    const resp = await axios.put(url, body, header)

    return handleResponse(resp)
  } catch (err: any) {
    throw handleResponse(err.response)
  }
}

export const patch = async (url: any, body: any) => {
  const header = await getHeaderInfo()

  try {
    const resp = await axios.patch(url, body, header)

    return handleResponse(resp)
  } catch (err: any) {
    throw handleResponse(err.response)
  }
}

export const deleteApi = async (url: any) => {
  const header = await getHeaderInfo()

  try {
    const resp = await axios.delete(url, header)

    return handleResponse(resp)
  } catch (err: any) {
    throw handleResponse(err.response)
  }
}

export const postImage = async (url: string, body: any) => {
  const header = await getFormDataHeader()
  const formData = new FormData()
  formData.append('file', body)
  try {
    const resp = await axios.put(url, formData, header)
    return handleResponse(resp)
  } catch (err: any) {
    throw handleResponse(err.response)
  }
}
