import axios from 'axios'
import { ApiProblem, problemDetailsSchema } from './problem'

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

api.interceptors.request.use(config => {
  const user = import.meta.env.VITE_DEV_AUTH_USER as string | undefined
  const role = import.meta.env.VITE_DEV_AUTH_ROLE as string | undefined
  if (import.meta.env.DEV && user && role) {
    config.headers['X-KArtSell-User'] = user
    config.headers['X-KArtSell-Role'] = role
  }
  return config
})

api.interceptors.response.use(
  response => response,
  error => {
    const parsed = problemDetailsSchema.safeParse(error.response?.data)
    if (parsed.success) throw new ApiProblem(parsed.data)
    throw error
  }
)
