import type { DebugLogEntry, DebugLogClientOptions, DebugLogLevel } from './types'

/**
 * Client for fetching debug logs from the API
 * Used by CLI and other tools to retrieve logs
 */
export class DebugLogClient {
  private apiUrl: string
  private headers: Record<string, string>

  constructor(options?: DebugLogClientOptions) {
    this.apiUrl = options?.apiUrl || 'http://localhost:5170'
    this.headers = options?.headers || {}
  }

  async getLogs(options?: {
    limit?: number
    level?: DebugLogLevel
    since?: string
    source?: string
  }): Promise<DebugLogEntry[]> {
    const params = new URLSearchParams()
    params.append('limit', (options?.limit || 100).toString())

    if (options?.level) params.append('level', options.level)
    if (options?.since) params.append('since', options.since)
    if (options?.source) params.append('source', options.source)

    try {
      const response = await global.fetch(`${this.apiUrl}/api/debug-logs?${params}`, {
        headers: this.headers
      })

      if (!response.ok) {
        throw new Error(`Failed to fetch logs: ${response.statusText}`)
      }

      const result = (await response.json()) as { logs?: DebugLogEntry[] }
      return result.logs || []
    } catch (error) {
      console.error('Failed to fetch debug logs:', error)
      return []
    }
  }

  async clear(): Promise<void> {
    try {
      const response = await global.fetch(`${this.apiUrl}/api/debug-logs`, {
        method: 'DELETE',
        headers: this.headers
      })

      if (!response.ok) {
        throw new Error(`Failed to clear logs: ${response.statusText}`)
      }
    } catch (error) {
      console.error('Failed to clear debug logs:', error)
    }
  }
}
