import { PublicError } from '@znet/shared'

type Query = Record<string, string | number | boolean | undefined>

/** Typed-enough HTTP client for the internal Catalog API. */
export class CatalogApiClient {
  constructor(
    private readonly baseUrl: string,
    private readonly token: string,
  ) {}

  async get<T = unknown>(path: string, query: Query = {}): Promise<T> {
    const url = new URL(`${this.baseUrl}${path}`)
    for (const [k, v] of Object.entries(query)) if (v !== undefined && v !== '') url.searchParams.set(k, String(v))
    const res = await fetch(url, { headers: { Authorization: `Bearer ${this.token}` }, signal: AbortSignal.timeout(15_000) })
    const body = (await res.json().catch(() => ({}))) as { message?: string; error?: string; issues?: unknown }
    if (res.status === 404) throw new PublicError(body.message ?? 'Not found', 404, 'not_found')
    if (res.status === 400) throw new PublicError(`Invalid request: ${JSON.stringify(body.issues ?? body.message)}`, 400)
    if (!res.ok) throw new Error(`Catalog API ${res.status} on ${path}`)
    return body as T
  }
}
