// {{ display_name }} MCP server — generated by mcpify. Do not hand-edit.
//
// A minimal stand-in target API for integration/e2e tests: responds 200 to
// every request with a JSON echo of the method/path/body it received, so
// tests can exercise the real HTTP call path (auth headers, circuit
// breaker, retries) without a live upstream API.

import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import type { AddressInfo } from 'node:net';

export interface MockApiServer {
  server: Server;
  url: string;
  requests: { method: string | undefined; url: string | undefined; headers: IncomingMessage['headers'] }[];
  close(): Promise<void>;
}

export async function startMockApiServer(): Promise<MockApiServer> {
  const requests: MockApiServer['requests'] = [];

  const server = createServer((request: IncomingMessage, response: ServerResponse) => {
    requests.push({ method: request.method, url: request.url, headers: request.headers });

    let body = '';
    request.on('data', (chunk) => (body += chunk));
    request.on('end', () => {
      response.writeHead(200, { 'Content-Type': 'application/json' });
      response.end(JSON.stringify({ ok: true, method: request.method, path: request.url, receivedBody: body || null }));
    });
  });

  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  const address = server.address() as AddressInfo;

  return {
    server,
    url: `http://127.0.0.1:${address.port}`,
    requests,
    close: () => new Promise<void>((resolve) => server.close(() => resolve())),
  };
}
