const { createEntityRouter } = require('../factories/router.factory');
const UsersService = require('../services/users');
const UsersDBApi = require('../db/api/users');
const { wrapAsync } = require('../helpers');

// Create base router with factory (includes all standard CRUD endpoints)
const router = createEntityRouter('users', UsersService, UsersDBApi, {
  permissionEntity: 'users',
  csvFields: ['id', 'firstName', 'lastName', 'phoneNumber', 'email'],
});

// Override GET /:id to remove password from response
// Note: This needs to be added BEFORE the router is exported
// The factory already registered this route, so we add middleware to sanitize
const originalGetById = router.stack.find(
  (layer) => layer.route?.path === '/:id' && layer.route?.methods?.get
);

if (originalGetById) {
  originalGetById.route.stack[0].handle = wrapAsync(async (req, res) => {
    // Call original handler with a custom response
    const payload = await UsersDBApi.findBy({ id: req.params.id });
    if (payload) {
      delete payload.password;
    }
    res.status(200).send(payload);
  });
}

module.exports = router;
