import type { FastifyInstance } from 'fastify';
import type { McpServerService } from '../services/mcp-server.service.js';
import type { InstanceService } from '../services/instance.service.js';

export function registerMcpServerRoutes(
  app: FastifyInstance,
  service: McpServerService,
  instanceService: InstanceService,
): void {
  app.get('/api/v1/servers', async () => {
    return service.list();
  });

  app.get<{ Params: { id: string } }>('/api/v1/servers/:id', async (request) => {
    return service.getById(request.params.id);
  });

  app.post('/api/v1/servers', async (request, reply) => {
    const server = await service.create(request.body);
    // Auto-reconcile: create instances to match replicas
    await instanceService.reconcile(server.id);
    reply.code(201);
    return server;
  });

  app.put<{ Params: { id: string } }>('/api/v1/servers/:id', async (request) => {
    const server = await service.update(request.params.id, request.body);
    // Re-reconcile after update (replicas may have changed)
    await instanceService.reconcile(server.id);
    return server;
  });

  app.delete<{ Params: { id: string } }>('/api/v1/servers/:id', async (request, reply) => {
    await service.delete(request.params.id);
    reply.code(204);
  });
}
