import axios, { AxiosInstance, AxiosError } from 'axios'

export class ApiError extends Error {
  constructor(
    public statusCode: number,
    message: string,
    public data?: unknown
  ) {
    super(message)
    this.name = 'ApiError'
  }
}

export function createApiClient(): AxiosInstance {
  const client = axios.create({
    baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3010',
    timeout: 30000,
    headers: {
      'Content-Type': 'application/json',
    },
  })

  client.interceptors.response.use(
    (response) => response,
    (error: AxiosError) => {
      if (error.response) {
        const data = error.response.data as { message?: string }
        throw new ApiError(
          error.response.status,
          data?.message || error.message,
          data
        )
      }
      throw new ApiError(0, error.message)
    }
  )

  return client
}

export const apiClient = createApiClient()
