import axios from 'axios'

export type ApiResponse<T = unknown> = {
  result: boolean
  msg?: string
  data?: T
}

const client = axios.create({ baseURL: '/api', timeout: 20_000 })

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

client.interceptors.response.use(
  (res) => res,
  (err) => {
    if (err.response?.status === 401) {
      localStorage.clear()
      if (!window.location.pathname.includes('/login')) window.location.href = '/login'
    }
    const msg = err.response?.data?.msg
    if (typeof msg === 'string' && msg && !err.message?.includes(msg)) {
      err.message = msg
    }
    return Promise.reject(err)
  },
)

export function unwrap<T>(payload: ApiResponse<T> | T): T {
  if (payload && typeof payload === 'object' && 'result' in (payload as object)) {
    const r = payload as ApiResponse<T>
    if (!r.result) throw new Error(r.msg || '요청 실패')
    return r.data as T
  }
  return payload as T
}

export function apiPrefix() {
  const role = localStorage.getItem('role')
  return role === 'SHOP' ? '/shop' : '/agent'
}

export default client
