import axios from 'axios'
import { parseCookies } from 'nookies'

const defaultOptions = {
	baseURL: '/api/',
	headers: {
		'Content-Type': 'application/json',
		Accept: 'application/json',
		'Access-Control-Allow-Headers':
			'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version',
		'Access-Control-Allow-Methods': 'GET,DELETE,PATCH,POST,PUT',
		'Access-Control-Allow-Origin': '*',
		'Access-Control-Allow-Credentials': true,
	},
}

// Create instance
const instance = axios.create(defaultOptions)

instance.defaults.withCredentials = true

// Set the AUTH token for any request
instance.interceptors.request.use(function (config) {
	const { token } = parseCookies()
	config.headers.Authorization = token ? `Bearer ${token}` : ''
	return config
})

export default instance
