// Auto-generated User routes
import type { FastifyInstance } from "fastify";
import { authenticate } from "../middleware/auth.js";
import { UserService } from "../services/user.js";
import type { CreateUserInput, UpdateUserInput } from "../types/index.js";

const service = new UserService();

export async function usersRoutes(app: FastifyInstance): Promise<void> {
  // All routes require authentication
  app.addHook("onRequest", authenticate);

  // GET /api/users — list
  app.get("/", async (request, reply) => {
    const items = service.list();
    return { data: items };
  });

  // GET /api/users/:id — get by id
  app.get<{ Params: { id: string } }>("/:id", async (request, reply) => {
    const item = service.getById(request.params.id);
    if (!item) {
      return reply.status(404).send({ error: "Not Found", message: "User not found", statusCode: 404 });
    }
    return { data: item };
  });

  // POST /api/users — create
  app.post<{ Body: CreateUserInput }>("/", async (request, reply) => {
    const item = service.create(request.body);
    return reply.status(201).send({ data: item });
  });

  // PUT /api/users/:id — update
  app.put<{ Params: { id: string }; Body: UpdateUserInput }>("/:id", async (request, reply) => {
    const item = service.update(request.params.id, request.body);
    if (!item) {
      return reply.status(404).send({ error: "Not Found", message: "User not found", statusCode: 404 });
    }
    return { data: item };
  });

  // DELETE /api/users/:id — delete
  app.delete<{ Params: { id: string } }>("/:id", async (request, reply) => {
    const deleted = service.delete(request.params.id);
    if (!deleted) {
      return reply.status(404).send({ error: "Not Found", message: "User not found", statusCode: 404 });
    }
    return reply.status(204).send();
  });
}
