import axios, { AxiosError } from 'axios'
import { useAuthStore, type BanInfo } from '@/store/auth'

const API_URL = import.meta.env.VITE_API_URL || '/api/v1'

const client = axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json',
  },
})

// Request interceptor to add auth token
client.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// Helper to check if detail is ban info object
function isBanInfo(detail: unknown): detail is BanInfo {
  return (
    typeof detail === 'object' &&
    detail !== null &&
    'banned_at' in detail &&
    'reason' in detail
  )
}

// Response interceptor to handle errors
client.interceptors.response.use(
  (response) => response,
  (error: AxiosError<{ detail: string | BanInfo }>) => {
    // Unauthorized - redirect to login (but not for auth endpoints)
    if (error.response?.status === 401) {
      const url = error.config?.url || ''
      const isAuthEndpoint = url.includes('/auth/login') || url.includes('/auth/register') || url.includes('/auth/2fa')

      if (!isAuthEndpoint) {
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        window.location.href = '/login'
      }
    }

    // Forbidden - check if user is banned
    if (error.response?.status === 403) {
      const detail = error.response.data?.detail
      if (isBanInfo(detail)) {
        // User is banned - set ban info in store
        useAuthStore.getState().setBanned(detail)
      }
    }

    // Server error or network error - redirect to 500 page
    if (
      error.response?.status === 500 ||
      error.response?.status === 502 ||
      error.response?.status === 503 ||
      error.response?.status === 504 ||
      error.code === 'ERR_NETWORK' ||
      error.code === 'ECONNABORTED'
    ) {
      // Only redirect if not already on error page
      if (!window.location.pathname.startsWith('/500') && !window.location.pathname.startsWith('/error')) {
        window.location.href = '/500'
      }
    }

    return Promise.reject(error)
  }
)

export default client
