/**
 * Server Factory for Testing
 * Creates Fastify server instances for testing
 */

import { FastifyInstance } from 'fastify';
import Fastify from 'fastify';
import { getEnv } from '@the-order/shared';

export interface ServerFactoryOptions {
  port?: number;
  logger?: boolean;
  [key: string]: unknown;
}

export async function createTestServer(
  routes: (server: FastifyInstance) => Promise<void>,
  options: ServerFactoryOptions = {}
): Promise<FastifyInstance> {
  const server = Fastify({
    logger: options.logger ?? false,
    requestIdLogLabel: 'requestId',
    disableRequestLogging: !options.logger,
  });

  // Register routes
  await routes(server);

  // Health check
  server.get('/health', () => {
    return { status: 'ok' };
  });

  if (options.port) {
    await server.listen({ port: options.port, host: '0.0.0.0' });
  }

  return server;
}

export function closeTestServer(server: FastifyInstance): Promise<void> {
  return server.close();
}

