import type { FastifyInstance } from 'fastify';
import type { UserService } from '../services/user.service.js';

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

  app.get<{ Params: { id: string } }>('/api/v1/users/:id', async (request) => {
    // Support lookup by email (contains @) or by id
    const idOrEmail = request.params.id;
    if (idOrEmail.includes('@')) {
      return service.getByEmail(idOrEmail);
    }
    return service.getById(idOrEmail);
  });

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

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