import axios from 'axios'
import router from './router'
import { useAuthStore } from './store/postulanteStore'

const apiPostulante = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' }
})

// Interceptor para agregar token del postulante
apiPostulante.interceptors.request.use(config => {
  const postulanteStore = useAuthStore()
  if (postulanteStore.token) {
    config.headers.Authorization = `Bearer ${postulanteStore.token}`
  }
  return config
})

// Manejo de errores (401)
apiPostulante.interceptors.response.use(
  response => response,
  error => {
    const postulanteStore = useAuthStore()
    if (error.response?.status === 401) {
      postulanteStore.logout()
      router.push('/login-postulante')
    }
    return Promise.reject(error)
  }
)

export default apiPostulante
