import type { Instrumentation } from "next";

export async function register() {
  // The scheduler needs Node APIs and the database, so never load it in another runtime.
  if (process.env.NEXT_RUNTIME !== "nodejs") return;

  const { env } = await import("@/server/env");
  if (env.SCHEDULER_MODE !== "internal") return;

  const { startSchedulerTicker } = await import("@/server/scheduler/ticker");
  startSchedulerTicker();
}

export const onRequestError: Instrumentation.onRequestError = async (error, request, context) => {
  const { logger } = await import("@/server/logger");
  logger.error("server.unexpected_error", {
    error,
    digest: typeof error === "object" && error !== null && "digest" in error ? String(error.digest) : undefined,
    method: request.method,
    path: request.path,
    routePath: context.routePath,
    routeType: context.routeType,
  });
};
