const express = require('express');
const {authenticate, requirePermission} = require('../middleware/auth');
const userService = require('../services/userService');
const {asyncHandler} = require('../utils/asyncHandler');
const {success} = require('../utils/apiResponse');

const router = express.Router();

router.get('/', authenticate, requirePermission('users.view'), asyncHandler(async (req, res) => {
  const data = await userService.listUsers(req.user.shop_id, req.query);
  return success(res, data);
}));

router.post('/', authenticate, requirePermission('users.create'), asyncHandler(async (req, res) => {
  const data = await userService.createUser(req.user.shop_id, req.user.id, req.body);
  return success(res, data, 'User created');
}));

router.put('/:id', authenticate, requirePermission('users.edit'), asyncHandler(async (req, res) => {
  const data = await userService.updateUser(req.user.shop_id, req.user.id, req.params.id, req.body);
  return success(res, data, 'User updated');
}));

router.delete('/:id', authenticate, requirePermission('users.delete'), asyncHandler(async (req, res) => {
  await userService.deleteUser(req.user.shop_id, req.user.id, req.params.id);
  return success(res, {}, 'User deleted');
}));

module.exports = router;
