import type { FastifyInstance } from 'fastify';
import type { GroupService } from '../services/group.service.js';

export function registerGroupRoutes(
  app: FastifyInstance,
  service: GroupService,
): void {
  app.get('/api/v1/groups', async () => {
    return service.list();
  });

  app.get<{ Params: { id: string } }>('/api/v1/groups/:id', async (request) => {
    // Try by ID first, fall back to name lookup
    try {
      return await service.getById(request.params.id);
    } catch {
      return service.getByName(request.params.id);
    }
  });

  app.post('/api/v1/groups', async (request, reply) => {
    const group = await service.create(request.body);
    reply.code(201);
    return group;
  });

  app.put<{ Params: { id: string } }>('/api/v1/groups/:id', async (request) => {
    return service.update(request.params.id, request.body);
  });

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