import { wrapAsyncHandler } from "@batch-cooking/express-tools";
import {
  auditBatchQuerySchema,
  submitTrainingSuggestionsSchema,
  workerBatchQuerySchema,
  workerHeartbeatSchema,
} from "@batch-cooking/shared";
import { Router } from "express";
import { requireInternalWorker } from "../../middlewares/require-internal-worker.js";
import {
  getAuditBatch,
  getPendingCorrections,
  recordWorkerHeartbeat,
  submitTrainingSuggestions,
} from "./tech-step-worker.service.js";

/**
 * Router mounted at `/internal/tech-steps` in app.ts — every route requires
 * {@link requireInternalWorker}, never {@link requireAuth}
 * (`middlewares/require-auth.ts`): this is `services/tech-step-llm-worker`
 * authenticating as itself, not a user session. See that middleware's own
 * doc comment for why the two are deliberately separate mechanisms.
 */
export const techStepWorkerRouter = Router();

techStepWorkerRouter.get(
  "/audit-batch",
  requireInternalWorker,
  wrapAsyncHandler(async (req, res) => {
    const input = auditBatchQuerySchema.parse(req.query);
    res.status(200).json(await getAuditBatch(input.locale, input.limit));
  }),
);

techStepWorkerRouter.get(
  "/pending-corrections",
  requireInternalWorker,
  wrapAsyncHandler(async (req, res) => {
    const input = workerBatchQuerySchema.parse(req.query);
    res.status(200).json(await getPendingCorrections(input.limit));
  }),
);

techStepWorkerRouter.post(
  "/training-suggestions",
  requireInternalWorker,
  wrapAsyncHandler(async (req, res) => {
    const input = submitTrainingSuggestionsSchema.parse(req.body);
    res.status(201).json(await submitTrainingSuggestions(input));
  }),
);

/**
 * Liveness ping from the worker (which has no inbound HTTP surface of its
 * own) — upserts its `WorkerHeartbeat` row so the admin monitoring board
 * can show it as up / stale / down and surface its last job result. Sent
 * on boot, on every scheduler tick, and after each job.
 */
techStepWorkerRouter.post(
  "/heartbeat",
  requireInternalWorker,
  wrapAsyncHandler(async (req, res) => {
    const input = workerHeartbeatSchema.parse(req.body);
    await recordWorkerHeartbeat(input);
    res.status(200).json({ ok: true });
  }),
);
