import { Packages } from '@/types/Packages'
import { Stats } from '@/types/Stats'

export class ApiClient {
  private readonly baseUrl: string

  constructor() {
    this.baseUrl = import.meta.env.VITE_BASE_URL
  }

  async fetch<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
    const url = `${this.baseUrl}${endpoint}`

    try {
      const response = await fetch(url, options)

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      return await response.json()
    } catch (error) {
      console.error(`Error fetching from ${url}:`, error)
      throw error // Re-throw to allow handling by caller
    }
  }

  async getPackages(
    params: {
      limit?: string | number
      offset?: string | number
      status?: string
    } = {}
  ): Promise<Packages> {
    const { limit = 0, offset = 0, status } = params

    let endpoint = `/packages?limit=${limit}&offset=${offset}`
    if (status) {
      endpoint += `&status=${status}`
    }

    return this.fetch<Packages>(endpoint)
  }

  async getStats(): Promise<Stats> {
    return this.fetch<Stats>('/stats')
  }
}

export const apiClient = new ApiClient()
