import { createServer } from 'http'
import { getFixture } from '../fixtures/api-responses.js'

/**
 * Simple HTTP mock server for E2E tests.
 * This is needed because spawned CLI processes can't access in-process mocks.
 */
export class MockServer {
  constructor(port = 0) {
    this.port = port
    this.server = null
    this.handlers = new Map()
  }

  /**
   * Register a mock response for a path.
   */
  mock(method, path, response, statusCode = 200) {
    const key = `${method} ${path}`
    this.handlers.set(key, { response, statusCode })
  }

  /**
   * Start the mock server.
   */
  async start() {
    return new Promise((resolve, reject) => {
      this.server = createServer((req, res) => {
        const key = `${req.method} ${req.url}`
        const handler = this.handlers.get(key)
        
        if (handler) {
          res.statusCode = handler.statusCode
          // DELETE requests with 204 should have no content
          if (handler.statusCode === 204) {
            res.end()
          } else {
            res.setHeader('Content-Type', 'application/json')
            res.end(JSON.stringify(handler.response))
          }
        } else {
          // Default 404 for unmocked endpoints
          res.statusCode = 404
          res.end(JSON.stringify({ error: 'Not found' }))
        }
      })

      this.server.listen(this.port, () => {
        this.port = this.server.address().port
        resolve(`http://localhost:${this.port}/v2`)
      })

      this.server.on('error', reject)
    })
  }

  /**
   * Stop the mock server.
   */
  async stop() {
    return new Promise((resolve) => {
      if (this.server) {
        this.server.close(resolve)
      } else {
        resolve()
      }
    })
  }

  /**
   * Set up common FCP API mocks.
   */
  setupCommonMocks() {
    // Availability endpoint
    this.mock('GET', '/v2/spot/availability', getFixture('availability.withInstances'))
    
    // SSH keys
    this.mock('GET', `/v2/projects/${process.env.FCP_PROJECT}/ssh-keys`, { ssh_keys: [] })
    this.mock('POST', `/v2/projects/${process.env.FCP_PROJECT}/ssh-keys`, { id: 'key-123' }, 201)
    
    // Bids list
    this.mock('GET', `/v2/spot/bids?project=${process.env.FCP_PROJECT}`, getFixture('bidsList.mixed'))
  }
}

/**
 * Create and start a mock server for E2E tests.
 */
export async function createMockServer() {
  const server = new MockServer()
  const baseUrl = await server.start()
  return { server, baseUrl }
}