import axios from 'axios'
// import Cookies from 'js-cookie'
// import router from '@/router'

const ajax = axios.create({
	baseURL: import.meta.env.VITE_APP_API_URL,
	withCredentials: true,
	timeout: 5000
})

export const request = (url, method = 'GET', params = {}, config = {}) => {

	method = method.toUpperCase()
	switch (method) {
		case 'GET':
			return ajax.get(url, { params, ...config })
		case 'POST':
			return ajax.post(url, params, config)
		default:
			return ajax.get(url, { params, ...config })
	}
}

ajax.interceptors.request.use(
	(config) => {

		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)

ajax.interceptors.response.use(
	(response) => {
		// refreshToken(response)
		return response.data
	},
	(error) => {
		if (error.response) {
			switch (error.response.status) {
				case 401:
				// console.log('response 401')
				// Cookies.remove('token', { expires: 30, domain: import.meta.env.VITE_APP_SSO_DOMAIN })
				// Cookies.remove('uid', { expires: 30, domain: import.meta.env.VITE_APP_SSO_DOMAIN })

				// router.replace({
				// 	path: '/login',
				// 	query: { redirect: router.currentRoute.fullPath }
				// })
			}
		}
		return Promise.reject(error);
	}
)

function refreshToken(response) {
	let token = response.headers.authorization
	if (token) {
		// Cookies.set('token', res.data.token, { expires: 30, domain: import.meta.env.VITE_APP_SSO_DOMAIN })
	}
}
