import axios from 'axios'
import API from '../api/index'

export default {
  install: (app) => {
    const baseUrl: string = 'http://localhost:4002'

    const request = axios.create({
      baseURL: baseUrl,
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json'
      }
    })

    const errorHandler = (error) => {
      if (!error.response) {
        // store.dispatch("alert/showMessage", {
        //   type: "error",
        //   message: "Tidak bisa terkoneksi dengan API",
        // });
        throw new Error('Failed to connect API')
      }
      if (error.response.status == 422) {
        throw error
      }
      const errorMessage = error.response.data.error
      // if (error.response.status === 401) {
      //   localStorage.removeItem('token')
      //   localStorage.removeItem('user')
      //   window.location = '/auth'
      // }
      // const alertMessage =
      //   error.response.data.code === "VALIDATION_ERROR"
      //     ? error.response.data.data[0].msg
      //     : errorMessage;
      // store.dispatch("alert/showMessage", {
      //   type: "error",
      //   message: alertMessage,
      // });
      throw new Error(errorMessage)
    }

    const successHandler = (response) => {
      return response
    }

    const requestHandler = (request) => {
      if (localStorage.getItem('token') != null) {
        request.headers.Authorization = `Bearer ${localStorage.getItem('token')}`
      }
      return request
    }
    request.interceptors.request.use((request) => requestHandler(request))
    request.interceptors.response.use(
      (response) => successHandler(response),
      (error) => errorHandler(error)
    )
    app.config.globalProperties.$api = new API(request)
    app.provide('api', new API(request))
  }
}
