// Node.js 런타임 전용 instrumentation (fs, path 등 Node API 사용)
// 실제 로직. src/instrumentation.ts 에서 NEXT_RUNTIME==="nodejs" 일 때만 동적 import.
import fs from "fs/promises";
import path from "path";
import type { Instrumentation } from "next";

const LOG_PATH = "logs/api-errors.log";

async function appendLog(line: string) {
  try {
    const full = path.join(process.cwd(), LOG_PATH);
    await fs.mkdir(path.dirname(full), { recursive: true });
    await fs.appendFile(full, line);
  } catch {
    // logging must never crash the app
  }
}

export function registerNode() {
  const origError = console.error;
  console.error = (...args: unknown[]) => {
    origError.apply(console, args);
    const body = args
      .map((a) =>
        a instanceof Error ? `${a.message}\n${a.stack ?? ""}` : typeof a === "string" ? a : JSON.stringify(a),
      )
      .join(" ");
    void appendLog(`[${new Date().toISOString()}] [console.error] ${body}\n`);
  };
}

export const onRequestErrorNode: Instrumentation.onRequestError = async (err, request, context) => {
  const e = err as Error;
  const line =
    `[${new Date().toISOString()}] [uncaught] ${request.method ?? ""} ${request.path ?? ""} ` +
    `(${context.routePath ?? context.routerKind})\n${e.message}\n${e.stack ?? ""}\n\n`;
  await appendLog(line);
};
