import axios from 'axios'

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

export const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_URL,
  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

    if (status === 401) {
      console.warn('Unauthorized. Redirecting to login...')
      window.location.href = '/login'
    }

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

    if (status >= 500) {
      console.error('Server error:', error.response?.data?.message || 'Terjadi kesalahan server.')
    }

    return Promise.reject(error)
  }
)
