// src/lib/jobs/JobLogger.ts

/**
 * Logger für Hintergrund-Jobs mit strukturiertem Output
 */
export class JobLogger {
  private jobName: string
  private startTime: number

  constructor(jobName: string) {
    this.jobName = jobName
    this.startTime = Date.now()
  }

  info(message: string, data?: unknown): void {
    console.log(
      `[${this.timestamp()}] [${this.jobName}] INFO: ${message}`,
      data !== undefined ? data : ''
    )
  }

  warn(message: string, data?: unknown): void {
    console.warn(
      `[${this.timestamp()}] [${this.jobName}] WARN: ${message}`,
      data !== undefined ? data : ''
    )
  }

  error(message: string, error?: unknown): void {
    console.error(
      `[${this.timestamp()}] [${this.jobName}] ERROR: ${message}`,
      error !== undefined ? error : ''
    )
  }

  debug(message: string, data?: unknown): void {
    if (process.env.NODE_ENV === 'development' || process.env.DEBUG) {
      console.log(
        `[${this.timestamp()}] [${this.jobName}] DEBUG: ${message}`,
        data !== undefined ? data : ''
      )
    }
  }

  /**
   * Log mit Dauer seit Job-Start
   */
  elapsed(message: string): void {
    const elapsed = Date.now() - this.startTime
    console.log(
      `[${this.timestamp()}] [${this.jobName}] INFO: ${message} (${elapsed}ms elapsed)`
    )
  }

  /**
   * Zusammenfassung am Ende des Jobs
   */
  summary(results: {
    success: boolean
    processed?: number
    errors?: number
    duration?: number
  }): void {
    const duration = results.duration || Date.now() - this.startTime
    const status = results.success ? 'SUCCESS' : 'FAILED'

    console.log(
      `[${this.timestamp()}] [${this.jobName}] ${status}: ` +
        `Processed: ${results.processed || 0}, ` +
        `Errors: ${results.errors || 0}, ` +
        `Duration: ${duration}ms`
    )
  }

  private timestamp(): string {
    return new Date().toISOString()
  }
}

export default JobLogger
