import { ToastEventBus } from 'primevue'

const instance = $fetch.create({
  baseURL: __API_BASE_URL__,
  credentials: 'include',
  retry: false,
  onResponseError({ request, response }) {
    if (!import.meta.client)
      return

    if (typeof request === 'string' && request.endsWith('/me'))
      return

    const message = response._data.error || 'Something went wrong'

    ToastEventBus.emit('add', { severity: 'error', summary: 'Error', detail: message, closable: false, life: 3000 })
  },
})

// function instance(url: string, request: Request) {
//   console.log(url)
//   return fetch({
//     url: `https://api.koptilnya.xyz${url}`,
//     credentials: 'include',
//     method: 'GET',
//     headers: {
//       'Accept': 'application/json',
//       'Content-Type': 'application/json',
//       ...request.headers,
//     },
//     ...request,
//     body: request.body ? JSON.stringify(request.body) : undefined,
//   })
// }

// async function instance(url: string, options: Partial<Request> = {}) {
//   const response = await fetch(`https://api.koptilnya.xyz/chad${url}`, {
//     method: options.method || 'GET',
//     headers: {
//       'Content-Type': 'application/json',
//       ...(options.headers || {}),
//     },
//     body: JSON.stringify(options.body ?? {}),
//     responseType: 2,
//     credentials: 'include',
//   })
//
//   const data = await response.json()
//
//   if (response.status >= 400) {
//     if (!import.meta.client)
//       return
//
//     const message = data?.error || 'Something went wrong'
//
//     ToastEventBus.emit('add', { severity: 'error', summary: 'Error', detail: message, closable: false, life: 3000 })
//
//     throw new Error(`HTTP ${response.status}: ${data?.message || 'Ошибка'}`)
//   }
//
//   return data
// }

export default instance
