import { wrapAsyncHandler } from "@batch-cooking/express-tools";
import { listPlaceholdersQuerySchema, markPlaceholdersReviewedSchema } from "@batch-cooking/shared";
import { Router } from "express";
import { requireAdmin } from "../../middlewares/require-admin.js";
import {
  listPlaceholderGroups,
  markPlaceholdersReviewed,
  pruneOrphanPlaceholders,
} from "./admin-catalog.service.js";

/**
 * Router mounted at `/admin/catalog` (via `admin.routes.ts`) — every route
 * behind {@link requireAdmin}. Surfaces the off-catalog ingredient
 * "placeholders" users typed when the seeded catalog fell short, so a
 * maintainer can see what's missing and mark gaps as handled.
 */
export const adminCatalogRouter = Router();

adminCatalogRouter.get(
  "/placeholders",
  requireAdmin,
  wrapAsyncHandler(async (req, res) => {
    res.status(200).json(await listPlaceholderGroups(listPlaceholdersQuerySchema.parse(req.query)));
  }),
);

adminCatalogRouter.patch(
  "/placeholders/mark-reviewed",
  requireAdmin,
  wrapAsyncHandler(async (req, res) => {
    res
      .status(200)
      .json(await markPlaceholdersReviewed(markPlaceholdersReviewedSchema.parse(req.body)));
  }),
);

/** Deletes placeholder rows no recipe references any more — see {@link pruneOrphanPlaceholders}. */
adminCatalogRouter.post(
  "/placeholders/prune-orphans",
  requireAdmin,
  wrapAsyncHandler(async (_req, res) => {
    res.status(200).json(await pruneOrphanPlaceholders());
  }),
);
