import axios from "axios"

const instance = axios.create({
  baseURL: "http://localhost:3000/api",
  headers: { "Content-Type": "application/json" },
  withCredentials: true, // <-- refresh cookie için şart
})

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

instance.interceptors.response.use(
  (res) => res,
  async (error) => {
    const original = error.config

    if (error.response?.status === 401 && !original?._retry) {
      original._retry = true
      try {
        // refresh cookie ile yeni access token al
        const { data } = await instance.post("/auth/refresh")
        localStorage.setItem("token", data.token)

        original.headers = original.headers || {}
        original.headers.Authorization = `Bearer ${data.token}`
        return instance(original)
      } catch (e) {
        // refresh de başarısızsa logout
        localStorage.removeItem("user")
        localStorage.removeItem("token")
        window.location.href = "/"
        return Promise.reject(e)
      }
    }

    return Promise.reject(error)
  }
)

export default instance
