import { defineBoot } from '#q-app/wrappers'
import axios, { type AxiosError, type AxiosRequestConfig } from 'axios'
import { Notify } from 'quasar'

declare module 'axios' {
  export interface AxiosRequestConfig {
    suppressNotify?: boolean
  }
}

class ServerError extends Error {
  constructor(
    public code: string,
    message: string
  ) {
    super(message)
    this.name = 'ServerError'
  }
}

const api = axios.create({
  baseURL: '/api/admin',
  withCredentials: true
})

api.interceptors.response.use(
  response => response,
  (error: AxiosError<{ error?: { code: string; message: string } }>) => {
    const errorData = error.response?.data?.error || {
      code: 'ZERO',
      message: error.message || 'Unknown error'
    }

    const serverError = new ServerError(errorData.code, errorData.message)

    if (error.config && !(error.config as AxiosRequestConfig).suppressNotify) {
      Notify.create({
        type: 'negative',
        message:  errorData.code + ': ' + errorData.message,
        icon: 'mdi-alert-outline',
      })
    }

    return Promise.reject(serverError)
  }
)

export default defineBoot(({ app }) => {
  app.config.globalProperties.$api = api
})

export { api, ServerError }
