import express from 'express';
import { wrapAsync } from '@/api/http/request';
import permissions from '@/middlewares/check-permissions';
import type { CrudController } from '@/api/controllers/shared/crud-controller';

/**
 * Wires the 9 generic-CRUD routes (guarded by `checkCrudPermissions(permission)`)
 * to a controller built by `createCrudController`.
 */
export function createCrudRouter(
  controller: CrudController,
  { permission }: { permission: string },
): express.Router {
  const router = express.Router();

  router.use(permissions.checkCrudPermissions(permission));

  router.post('/', wrapAsync(controller.create));
  router.post('/bulk-import', wrapAsync(controller.bulkImport));
  router.put('/:id', wrapAsync(controller.update));
  router.delete('/:id', wrapAsync(controller.remove));
  router.post('/deleteByIds', wrapAsync(controller.deleteByIds));
  router.get('/', wrapAsync(controller.list));
  router.get('/count', wrapAsync(controller.count));
  router.get('/autocomplete', wrapAsync(controller.autocomplete));
  router.get('/:id', wrapAsync(controller.findById));

  return router;
}
