import express from "express";
import {
  listRecords,
  getRecordByPk,
  createRecord,
  updateRecordByPk,
  deleteRecordByPk,
} from "../controllers/genericCrudController.js";

export function createCrudRouter(tableName, primaryKeys) {
  const router = express.Router();
  const pkPath = primaryKeys.map((k) => `:${k}`).join("/");

  router.get("/", listRecords(tableName));
  router.get(`/${pkPath}`, getRecordByPk(tableName, primaryKeys));
  router.post("/", createRecord(tableName));
  router.put(`/${pkPath}`, updateRecordByPk(tableName, primaryKeys));
  router.delete(`/${pkPath}`, deleteRecordByPk(tableName, primaryKeys));

  return router;
}

/** Mount multiple table CRUD routers on one Express router. */
export function mountCrudTables(router, tableDefs) {
  for (const [tableName, primaryKeys] of tableDefs) {
    router.use(`/${tableName}`, createCrudRouter(tableName, primaryKeys));
  }
}
