import axios from "axios"
import Cookies from "js-cookie"

// Flag to prevent multiple network error alerts
let networkErrorAlertShown = false

export const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_BASE_URL,
  headers: {
    "ngrok-skip-browser-warning": "true"
  }
})

// Add request interceptor to include Authorization header
api.interceptors.request.use(
  config => {
    const token = Cookies.get("iit_token")
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// Add response interceptor to handle unauthorized errors
api.interceptors.response.use(
  response => {
    return response
  },
  error => {
    // Check for network errors (no internet connection)
    if (!error.response && (error.code === "ERR_NETWORK" || error.message === "Network Error")) {
      if (typeof window !== "undefined" && !networkErrorAlertShown) {
        networkErrorAlertShown = true
        alert("No internet connection. Please check your network and try again.")

        // Reset the flag after 30 seconds to allow future alerts
        setTimeout(() => {
          networkErrorAlertShown = false
        }, 30000)
      }
      return Promise.reject(error)
    }

    if (error.response?.status === 401) {
      // Only handle 401 errors for non-auth routes
      if (typeof window !== "undefined") {
        const currentPath = window.location.pathname
        const pathnameLocale = currentPath.split('/')[1]
        const locale = ['en', 'fr'].includes(pathnameLocale) ? pathnameLocale : 'en'
        const isAuthRoute = currentPath.match(new RegExp(`^/${locale}/(sign-in|sign-up)`)) || currentPath.startsWith('/sign-in') || currentPath.startsWith('/sign-up')
        if (!isAuthRoute) {
          // Clear the token cookie
          Cookies.remove("iit_token")
          // Redirect to login screen
          window.location.href = `/${locale}/sign-in`
        }
      }
    }
    return Promise.reject(error)
  }
)


