import axios from 'axios'
import { toast } from 'react-toastify'

const getToken = () => {
  return localStorage.getItem('authToken')
}

export const api = axios.create({
  baseURL: 'http://127.0.0.1:4000/api/v1',
  headers: {
    'Content-Type': 'application/json'
  },
  timeout: 10000
})

api.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

api.interceptors.response.use(
  response => response,
  error => {
    const status = error.response?.status
    const currentPath = window.location.pathname

    if (status === 401 && !currentPath.endsWith('/login')) {
      localStorage.removeItem('user')
      localStorage.removeItem('authToken')
      window.location.href = '/login'
    }

    if (status === 403) {
      console.error('Forbidden: Kamu tidak punya akses.')
    }

    if (status >= 500) {
      toast.error(error.response?.data?.errors[0].cause || 'Terjadi kesalahan server.')
    }

    return Promise.reject(error)
  }
)
