import Fastify from 'fastify';
import type { FastifyInstance } from 'fastify';
import type { McpdConfig } from './config/index.js';
import { registerSecurityPlugins } from './middleware/security.js';
import { errorHandler } from './middleware/error-handler.js';
import { registerHealthRoutes } from './routes/health.js';
import type { HealthDeps } from './routes/health.js';
import type { AuthDeps } from './middleware/auth.js';
import type { AuditDeps } from './middleware/audit.js';

export interface ServerDeps {
  health: HealthDeps;
  auth?: AuthDeps;
  audit?: AuditDeps;
}

export async function createServer(config: McpdConfig, deps: ServerDeps): Promise<FastifyInstance> {
  const app = Fastify({
    logger: {
      level: config.logLevel,
    },
  });

  // Error handler
  app.setErrorHandler(errorHandler);

  // Security plugins
  await registerSecurityPlugins(app, config);

  // Health routes (no auth required)
  registerHealthRoutes(app, deps.health);

  return app;
}
