import { Router } from "express";
import { getTrace, listTraces } from "../services/traceLogger";
import { ApiError, ok } from "../utils/http";

export function buildHistoryRouter(): Router {
  const router = Router();

  router.get("/api/history", (_req, res) => {
    ok(res, {
      ok: true,
      items: listTraces(200)
    });
  });

  router.get("/api/history/:trace_id", (req, res, next) => {
    try {
      const traceId = String(req.params.trace_id);
      const trace = getTrace(traceId);
      if (!trace) {
        throw new ApiError("TRACE_NOT_FOUND", `Trace not found: ${traceId}`, 404);
      }
      ok(res, {
        ok: true,
        trace
      });
    } catch (error) {
      next(error);
    }
  });

  return router;
}
