// src/services/api.js
import axios from 'axios'
import qs from 'qs'
import { useAuthStore } from 'stores/authStore'

const api = axios.create({
  baseURL: 'http://localhost:8080/api',
  timeout: 180000,
  paramsSerializer: params =>
    qs.stringify(params, { arrayFormat: 'repeat' })
})

// REQUEST
api.interceptors.request.use((config) => {
  const auth = useAuthStore()
  const url = config.url || ''

  const isPublic =
    url.startsWith('/auth/login') ||
    url.startsWith('/auth/refresh') ||
    url.startsWith('/password/forgot') ||
    url.startsWith('/password/reset')


  if (!isPublic && auth?.token) {
    config.headers ||= {}
    config.headers.Authorization = `Bearer ${auth.token}`
  }

  return config
})

// RESPONSE
let isLoggingOut = false
api.interceptors.response.use(
  r => r,
  async (error) => {
    if (error?.response?.status === 401 && !isLoggingOut) {
      isLoggingOut = true
      try {
        useAuthStore().clearSession()
      } finally {
        isLoggingOut = false
      }
    }
    return Promise.reject(error)
  }
)

// HELPERS
export const get = (u, p = {}, c = {}) =>
  api.get(u, { params: p, ...c }).then(r => r.data)

export const post = (u, b = {}, c = {}) =>
  api.post(u, b, c).then(r => r.data)

export const put = (u, b = {}, c = {}) =>
  api.put(u, b, c).then(r => r.data)

export const del = (u, p = {}, c = {}) =>
  api.delete(u, { params: p, ...c }).then(r => r.data)

export const download = (u, p = {}, c = {}) =>
  api.get(u, { params: p, responseType: 'blob', ...c })
    .then(r => r.data)

export default api
