/* eslint-disable no-undef */
import type { DebugLogLevel } from './types'

/**
 * Simple debug logger for development
 * Sends logs to the debug-logs API endpoint
 */
export class DebugLogger {
  private apiUrl: string
  private source?: string
  private authToken?: string

  constructor(apiUrl = 'http://localhost:5170', source?: string) {
    this.apiUrl = apiUrl
    this.source = source
  }

  setAuthToken(token: string | undefined): void {
    this.authToken = token
  }

  /**
   * Internal log method
   */
  private log(level: DebugLogLevel, message: string, data?: Record<string, unknown>): void {
    // Use globalThis.fetch for universal browser/Node.js compatibility
    const fetchFn =
      typeof globalThis !== 'undefined' && globalThis.fetch
        ? globalThis.fetch
        : typeof window !== 'undefined' && window.fetch
          ? window.fetch
          : typeof global !== 'undefined' && global.fetch
            ? global.fetch
            : null

    if (!fetchFn) {
      // No fetch available, skip logging
      return
    }

    // Fire-and-forget HTTP request
    fetchFn(`${this.apiUrl}/api/debug-logs`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(this.authToken && { Authorization: `Bearer ${this.authToken}` })
      },
      body: JSON.stringify({
        level,
        message,
        source: this.source,
        data,
        timestamp: new Date().toISOString()
      })
    }).catch(() => {
      // Silent fail - this is development-only logging
      // We don't want logging failures to break the app
    })
  }

  debug(message: string, data?: Record<string, unknown>): void {
    this.log('DEBUG', message, data)
  }

  info(message: string, data?: Record<string, unknown>): void {
    this.log('INFO', message, data)
  }

  warn(message: string, data?: Record<string, unknown>): void {
    this.log('WARN', message, data)
  }

  error(message: string, data?: Record<string, unknown>): void {
    this.log('ERROR', message, data)
  }

  child(childSource: string): DebugLogger {
    const combinedSource = this.source ? `${this.source}:${childSource}` : childSource
    const child = new DebugLogger(this.apiUrl, combinedSource)
    child.authToken = this.authToken
    return child
  }
}
