import { registerOTel } from "@vercel/otel";
import { PgInstrumentation } from "@opentelemetry/instrumentation-pg";
import type { Instrumentation } from "next";

export function register() {
  registerOTel({
    serviceName: process.env.OTEL_SERVICE_NAME || "sidetrail-app",
    instrumentations: [new PgInstrumentation()],
  });
}

export const onRequestError: Instrumentation.onRequestError = async (err, request, context) => {
  const error = err as Error & { digest?: string; cause?: unknown };
  console.error("[onRequestError]", {
    error: {
      name: error.name,
      message: error.message,
      digest: error.digest,
      cause: error.cause,
      stack: error.stack,
    },
    request: {
      method: request.method,
      path: request.path,
    },
    context,
  });
};
