import { Router } from "express";

import { authenticate, authorize } from "../../middleware/auth.js";
import { validate } from "../../middleware/validate.js";
import { asyncHandler } from "../../utils/http.js";
import { createUser, deleteUser, listUsers, updateUser } from "./users.service.js";
import { userCreateSchema, userParamsSchema, userPatchSchema } from "./users.schemas.js";

export const usersRouter = Router();

usersRouter.get(
  "/",
  authenticate,
  authorize("admin"),
  asyncHandler(async (_request, response) => {
    response.json({ data: await listUsers() });
  })
);

usersRouter.post(
  "/",
  authenticate,
  authorize("admin"),
  validate({ body: userCreateSchema }),
  asyncHandler(async (request, response) => {
    const created = await createUser(request.body);
    response.status(201).json({ data: created });
  })
);

usersRouter.patch(
  "/:id",
  authenticate,
  authorize("admin"),
  validate({ params: userParamsSchema, body: userPatchSchema }),
  asyncHandler(async (request, response) => {
    const updated = await updateUser(request.params.id as string, request.body);
    response.json({ data: updated });
  })
);

usersRouter.delete(
  "/:id",
  authenticate,
  authorize("admin"),
  validate({ params: userParamsSchema }),
  asyncHandler(async (request, response) => {
    await deleteUser(request.params.id as string);
    response.status(204).send();
  })
);
