import axios from 'axios'

const api = axios.create({
  baseURL: '/api',
})

api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

api.interceptors.response.use(
  (response) => {
    // Sliding token expiration: if server sends new token, update localStorage
    const newToken = response.headers['x-new-token']
    if (newToken) {
      localStorage.setItem('token', newToken)
    }
    return response
  },
  (error) => {
    // Check for token refresh even on error responses
    const newToken = error.response?.headers?.['x-new-token']
    if (newToken) {
      localStorage.setItem('token', newToken)
    }

    const url = error.config?.url || ''
    // Don't redirect to login from the login/register/verify endpoints themselves
    const isAuthEndpoint = url.includes('/auth/login') || url.includes('/auth/register') ||
      url.includes('/auth/verify') || url.includes('/auth/reset') || url.includes('/auth/forgot')
    if (error.response?.status === 401 && !isAuthEndpoint) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    // Unverified email — clear token and redirect to login (will show resend option)
    if (error.response?.status === 403 && error.response?.headers?.['x-unverified'] === 'true') {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export default api
