import createFetch from 'openapi-fetch'
import type { paths } from '@/generated/alhp'

// Create a type-safe API client using the OpenAPI types
const apiClient = createFetch<paths>({
  baseUrl: import.meta.env.VITE_BASE_URL
})

/**
 * Get packages with optional filtering
 * @param params Query parameters for filtering packages
 * @returns Promise with the packages response
 */
export const getPackages = async (params: {
  status?: Array<
    | 'latest'
    | 'failed'
    | 'built'
    | 'skipped'
    | 'delayed'
    | 'building'
    | 'signing'
    | 'unknown'
    | 'queued'
  >
  pkgbase?: string
  exact?: boolean
  repo?: string
  offset: number
  limit: number
}) => {
  const { data, error } = await apiClient.GET('/packages', {
    params: {
      query: params
    }
  })

  if (error) {
    throw new Error(`Failed to fetch packages: ${(error as any).statusCode}`)
  }

  return data
}

/**
 * Get build statistics
 * @returns Promise with the stats response
 */
export const getStats = async () => {
  const { data, error } = await apiClient.GET('/stats')

  if (error) {
    throw new Error(`Failed to fetch stats: ${(error as any).statusCode || 'unknown error'}`)
  }

  return data
}

export default apiClient
