export async function onRequestError(
  err: Error & { digest?: string },
  request: {
    path: string
    method: string
    headers: Record<string, string>
  },
  context: {
    routePath: string
    routerKind: string
    routeType: string
  }
) {
  console.error(
    JSON.stringify({
      timestamp: new Date().toISOString(),
      type: "request_error",
      message: err.message,
      digest: err.digest,
      stack: err.stack,
      request: {
        path: request.path,
        method: request.method,
      },
      route: {
        path: context.routePath,
        kind: context.routerKind,
        type: context.routeType,
      },
    }, null, 2)
  )
}

export async function register() {
  // Only run in Node.js runtime, not Edge runtime
  if (process.env.NEXT_RUNTIME === "nodejs") {
    process.on("uncaughtException", (err) => {
      console.error(
        JSON.stringify({
          timestamp: new Date().toISOString(),
          type: "uncaughtException",
          message: err.message,
          stack: err.stack,
        }, null, 2)
      )
    })

    process.on("unhandledRejection", (reason) => {
      console.error(
        JSON.stringify({
          timestamp: new Date().toISOString(),
          type: "unhandledRejection",
          reason: String(reason),
        }, null, 2)
      )
    })
  }
}