import { useSpinnerStore } from '@/store/spinnerStore'
import axios from 'axios'

export const axiosInstance = (url: string | null | undefined) => {
  const baseURL = url || process.env.NEXT_PUBLIC_API_URL
  const instance = axios.create({
    baseURL,
    headers: {
      Accept: 'application/json',
    },
  })

  instance.interceptors.request.use(
    (config) => {
      // console.log('🚀 ~ config:', config)
      return config
    },
    (error) => {
      return Promise.reject(error)
    },
  )

  instance.interceptors.response.use(
    (response) => {
      response.data = transferResponse(response)
      return response
    },
    (error) => {
      // 에러 처리 로직
      return Promise.reject(error)
    },
  )

  return instance
}

// Request interceptor
// axios.interceptors.request.use(
//   (config) => {
//     // 여기에 토큰 추가 등의 공통 로직을 넣을 수 있습니다
//     return config
//   },
//   (error) => {
//     return Promise.reject(error)
//   },
// )

// Response interceptor
// axios.interceptors.response.use(
//   (response) => transferResponse(response),
//   (error) => {
//     // 에러 처리 로직
//     return Promise.reject(error)
//   },
// )

// response데이터가  array, object에 따라 분기하여 키 변환
export const transferResponse = (response: any) => {
  if (!response.data) return response.data

  // 배열인 경우 각 객체의 키를 변환
  if (Array.isArray(response.data)) {
    return response.data.map((item: any) => transformObjectKeys(item))
  }

  // 단일 객체인 경우
  return transformObjectKeys(response.data)
}

// camel case object 반환
export const transformObjectKeys = (obj: any): any => {
  if (Array.isArray(obj)) {
    return obj.map(transformObjectKeys)
  }

  if (obj !== null && typeof obj === 'object') {
    return Object.keys(obj).reduce((acc: any, key: string) => {
      let transformedKey = key

      // Handle uppercase snake_case (e.g., USER_NAME -> userName)
      // Handle lowercase snake_case (e.g., user_name -> userName)
      if (/^[A-Z_]+$/.test(key) || /^[a-z_]+$/.test(key)) {
        transformedKey = snakeToCamel(key)
      }
      // Handle single uppercase word (e.g., ROLE -> role)
      else if (/^[A-Z]+$/.test(key)) {
        transformedKey = key.toLowerCase()
      }
      // Preserve existing camelCase

      acc[transformedKey] = transformObjectKeys(obj[key])
      return acc
    }, {})
  }

  return obj
}

const snakeToCamel = (str: string): string => {
  return str.toLowerCase().replace(/([-_][a-z])/g, (group) => group.toUpperCase().replace('-', '').replace('_', ''))
}
