import { defineBoot } from '#q-app/wrappers'
import axios, { type AxiosError } from 'axios'
import { useAuthStore } from 'src/stores/auth'

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,
  async (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.response?.status === 401) {
      await useAuthStore().logout()
    }

    return Promise.reject(serverError)
  }
)

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

export { api, ServerError }