import { readFileSync, writeFileSync, existsSync } from 'fs'
import { join } from 'path'

/**
 * HTTP recorder placeholder for undici tests.
 * Since undici doesn't have built-in recording like nock,
 * this provides a minimal interface for compatibility.
 */
export class HttpRecorder {
  constructor(fixturePath) {
    this.fixturePath = fixturePath
    this.recording = false
  }

  /**
   * Start recording HTTP requests to file.
   * No-op for undici - recording should be done manually.
   */
  startRecording() {
    this.recording = true
    console.warn('HTTP recording not supported with undici. Use manual fixture creation.')
  }

  /**
   * Stop recording and return captured requests.
   */
  stopRecording() {
    this.recording = false
    return []
  }

  /**
   * Load and replay recorded HTTP interactions.
   * With undici, mocks should be set up explicitly in tests.
   */
  loadRecording() {
    if (!existsSync(this.fixturePath)) {
      console.warn(`No recording found at ${this.fixturePath}`)
      return []
    }

    // Load fixture for reference but don't apply mocks
    const recordings = JSON.parse(readFileSync(this.fixturePath, 'utf8'))
    return recordings
  }

  /**
   * Clean up all HTTP mocks.
   */
  cleanup() {
    // No cleanup needed for undici MockAgent
  }
}

/**
 * Create recorder for a specific test scenario.
 */
export function createRecorder(testName) {
  const fixturePath = join(process.cwd(), 'test', 'fixtures', `${testName}.json`)
  return new HttpRecorder(fixturePath)
}