import axios from 'axios'
// import Router from 'next/router'
import { destroyCookie, parseCookies } from 'nookies'

const { 'sevenpro-token': token } = parseCookies()

export const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_URL_API,
})

if (token) {
  api.defaults.headers.Authorization = `Bearer ${token}`
}

// api.interceptors.request.use(
//   (config) => {

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

api.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (error.response && error.response.status === 401) {
      // Remove o token inválido
      destroyCookie(null, 'sevenpro-token')

      // Redireciona para a página de login
      // Router.push('/login')
    }
    return Promise.reject(error)
  },
)
