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

export function registerInstanceRoutes(app: FastifyInstance, service: InstanceService): void {
  app.get<{ Querystring: { serverId?: string } }>('/api/v1/instances', async (request) => {
    return service.list(request.query.serverId);
  });

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

  app.delete<{ Params: { id: string } }>('/api/v1/instances/:id', async (request, reply) => {
    const { serverId } = await service.remove(request.params.id);
    // Reconcile: server will auto-create a replacement if replicas > 0
    await service.reconcile(serverId);
    reply.code(204);
  });

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

  app.get<{ Params: { id: string }; Querystring: { tail?: string } }>(
    '/api/v1/instances/:id/logs',
    async (request) => {
      const opts: { tail?: number } = {};
      if (request.query.tail) {
        opts.tail = parseInt(request.query.tail, 10);
      }
      return service.getLogs(request.params.id, opts);
    },
  );
}
